如何使用纯 Javascript 将选中的单选按钮的值存储在本地存储中?
我想将我选中的单选按钮存储在本地存储中,以便在页面重新加载时,它会在重新加载时检查最后一个选中的项目.
I'd like to store my checked radio button in local storage so that on a page reload it will have the last checked item check on the reload.
HTML:
<h3>Seconds Display:</h3>
<p id="secondsHidingText">Hiding seconds extends battery life</p>
  <input type="radio" name="seconds" value="show" checked="checked">Show  
<input type="radio" name="seconds" value="hide">Hide
这是我拥有的 javascript:
This is the javascript I have:
localStorage.setItem('seconds', options.seconds);
(当我点击保存按钮时运行)
(which runs when the save button I have is clicked)
和
document.getElementById('seconds').value = localStorage.getItem("seconds");
(在正在加载的文档上运行)
(which runs on document being loaded)
我收到以下错误:Uncaught TypeError: Cannot set property 'value' of null
如何在本地存储中存储和检索选中的单选按钮?如果可能的话,我正在寻找一种纯 JS 方式来实现这一点.
How do I store and retrieve the checked radio button to and from local storage? And if possible I'm looking for a pure JS way of accomplishing this.
谢谢!
您必须遍历单选按钮,然后设置值.类似这样的
You would have to iterate through the radio buttons and then set the value. Something like this
var radios = document.getElementsByName("seconds"); // list of radio buttons
var val = localStorage.getItem('seconds'); // local storage value
for(var i=0;i<radios.length;i++){
if(radios[i].value == val){
radios[i].checked = true; // marking the required radio as checked
}
}
我使用 jquery 只是为了方便地设置 localstorage 值.
I used jquery only to set the localstorage value in a convenient way.
这是一个演示