我已经获得了将表单数据保存到localstorage中的代码,然后通过替换<span id="recalledtext" >Dear Visitors</span>
来显示它。的innerHTML。
<HTML>
<head>
<script>
function myfunction1(){texttosave = document.getElementById('textline').value ; localStorage.setItem('mynumber', texttosave); } function myfunction2(){document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); }
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name"/> <button id="rememberer" onclick='myfunction1()'>Save</button>
<br>
Welcome<span id="recalledtext" >Dear Visitors</span> Refresh the page to see changes
</body>
</HTML>
它工作得很好,但我也想要一个删除数据按钮。所以我已将代码更改为:
<HTML>
<head>
<script>
function myfunction1(){texttosave = document.getElementById('textline').value ; localStorage.setItem('mynumber', texttosave); } function myfunction2(){document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } function myfunction3() localStorage.removeItem('mynumber'); return '';}
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name"/> <button id="rememberer" onclick='myfunction1()'>Save</button> <button id="recaller" onclick='myfunction3()'>Delete Your Name</button>
<br>
Welcome<span id="recalledtext" >Dear Visitors</span> Refresh the page to see changes
</body>
</HTML>.
但是在添加函数myfunction3()之后,代码完全停止了工作。
答案 0 :(得分:1)
我自己找到了答案。很长一段时间我很适合你,然后我开始检查JavaScript代码。有一个缺少的角色&#34; {&#34; 这是正确的代码
<HTML><head>
<script>
function myfunction1(){texttosave = document.getElementById('textline').value ; localStorage.setItem('mynumber', texttosave); } function myfunction2(){document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } function myfunction3() localStorage.removeItem('mynumber'); return '';}
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name"/> <button id="rememberer" onclick='myfunction1()'>remember text</button> <button id="recaller" onclick='myfunction3()'>Delete Your Name</button>
<br>
Welcome<span id="recalledtext" >Dear Visitors</span> Refresh the page to see changes
</body>
</HTML>