我想在页面重新加载时将数据保存在输入中,我不想 知道为什么我的代码不起作用。这是我的html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<label>nom:</label> <input type="text" value=""/></br>
<label>prenom:</label><input type="text" value=""/>
<script type="text/javascript">
window.onbeforeunload = function(){
localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
}
document.addEventListener("DOMContentLoaded",function(){
var nom = localStorage.getItem(nom);
var prnom = localStorage.getItem(prenom);
if(nom!==null&&prenom!==null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
});
</script>
</body>
</html>
答案 0 :(得分:1)
确保使用变量名称的引号:
localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);
或者您可以使用更简单的方法:
localStorage.nom = document.getElementsByTagName('input')[0].value;
window.onbeforeunload = function() {
var nom = localStorage.nom;
var prnom = localStorage.prenom;
if (nom !== null && prenom !== null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
};
&#13;
<label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
<label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />
&#13;