我有一个表单,我试图将字段保存到本地存储中,但警报显示为空,并且本地存储未保存
<form method="post">
<input type="text" name="name" id="name" class="stored form-control" value="" />
<button onclick="store()" type="button" id="myButton" class="btn />
</form>
function store(){
var inputName= document.getElementById("name");
window.localStorage.setItem("name", inputName.value);
alert(name);
}
答案 0 :(得分:1)
您必须调用 window.localStorage.getItem(“ name”)才能在警报中从本地存储获取名称。另外,您的按钮标签未正确关闭。我刚刚格式化了您的代码:
<!DOCTYPE html>
<html>
<head>
<title>Local Storage Demo</title>
<script>
function store(){
var inputName= document.getElementById("name");
window.localStorage.setItem("name", inputName.value);
alert(window.localStorage.getItem("name"));
}
</script>
</head>
<body>
<form>
<input type="text" name="name" id="name" />
<button onclick="store()" type="button" id="myButton">Save</button>
</form>
</body>
</html>