我有一个多个单选按钮的代码(嵌套在选项卡中),我需要在本地保存和恢复所有值。我尝试过使用cookies,但只保存了一个值。我试过" localStorage"但我想我需要一些帮助。基本思想是在每次点击时保存值并在" window.onload"上恢复它们。
如果更容易,我可以回到饼干!有经验吗?提前谢谢。
<html>
<head>
<title>Saving RadioButtons locally</title>
</head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script src="scripts/modernizr.js"></script>
<script type="text/javascript">
//this function runs everytime there is a click from the mouse to update and save the radio values (logicaly)
function saveState() {
//gets every object from the main form to read and save it.
localStorage.setItem("flag", "set");
var data = $("#mainform").serializeArray();
$.each(data, function(i, obj) {
localStorage.setItem(obj.name, obj.value);
});
console.log(data); //console shows only one object which is the first one (pid) with one value
}
//this function must be run each time the window loads to initialize the radio values (logicaly)
function onloadfunction() {
if (localStorage.getItem("flag") == "set") {
//gets every object from the main form to read and restore it.
var data = $("#mainform").serializeArray();
$.each(data, function(i, obj) {
$("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
});
}
}
window.onload=onloadfunction;
window.onbeforeunload=saveState;
//end of ideas...............
</script>
<body>
<form id="mainform" name='mainform'>
<div id="container" class="container">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#Cid">Cid</a></li>
<li><a data-toggle="tab" href="#Bid">Bid</a></li>
<!-- first tab -->
<!-- first radio box in first tab -->
</ul>
<div class="tab-content">
<div id="Cid" class="tab-pane fade in active">
<form name='pid'>
<input type="radio" id="p40" name="p" value="40">40
<input type="radio" id="p45" name="p" value="45">45
<input type="radio" id="p50" name="p" value="50">50
</form>
<!-- second radio box in first tab -->
<form name='BName'>
<input type="radio" id="B40" name="B" value="40">40
<input type="radio" id="B45" name="B" value="45">45
</form>
</div>
<!-- second tab -->
<!-- first radio box in second tab -->
<div id="Bid" class="tab-pane fade">
<form name='HName'>
<input type="radio" id="H40" name="H" value="40">40
<input type="radio" id="H45" name="H" value="45">45
<input type="radio" id="H50" name="H" value="50">50
</form>
</div>
</form>
</body>