function action() {
window.localStorage['header1'] = document.getElementById('header1').value;
window.localStorage['header2'] = document.getElementById('header2').value;
window.localStorage['header3'] = document.getElementById('header3').value;
window.localStorage['header4'] = document.getElementById('header4').value;
}
function action2() {
document.getElementById('header1').value = window.localStorage['header1'];
document.getElementById('header2').value = window.localStorage['header2'];
document.getElementById('header3').value = window.localStorage['header3'];
document.getElementById('header4').value = window.localStorage['header4'];
}
<body onload="action2()">
<input type="text" id="header1" name="header1" value="name1">
<input type="text" id="header2" name="header2" value="name2">
<input type="text" id="header3" name="header3" value="name3">
<input type="text" id="header4" name="header4" value="name4">
<p><button onclick="action()" type="button">Save me!</button></p>
</body>
答案 0 :(得分:0)
var len = 4;
for(var i = 0; i < len; i++) {
window.localStorage['header'+ i] = document.getElementById('header' + i).value;
}
最好将它全部存储在一个对象中,并将其添加到localstorage中,如下所示......
var len = 4;
var localObj = {};
for(var i = 0; i < len; i++) {
localObj['header'+ i] = document.getElementById('header' + i).value;
}
window.localStorage['headers'] = JSON.stringify(localObj);
然后你可以像下面一样检索它,它会给你一个对象,headers.headers1等......
JSON.parse(localStorage.getItem('headers'));
答案 1 :(得分:0)
要合并函数,您可以使用type
参数来指定是否要使用本地存储的DOM。
然后你可以使用for循环来循环所有元素,这样你就不会重复了。
function action(type) {
for(var i = 1; i <= 4; i++) {
if(type === "element") {
document.getElementById('header' + i).value = window.localStorage['header' +i];
} else if(type === "storage") {
window.localStorage['header' +i] = document.getElementById('header' +i).value;
}
}
}
action("storage"); // equivalent to: action()
action("element"); // equivalent to: action2();