我已将此代码用于将表单数据保存到localstorage
<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 Visitor,</span> Refresh the page to see changes
</body>
</HTML>
如果输入您的姓名并单击“保存”按钮,则会将您的姓名保存到localstorage中。然后,如果您刷新页面,您将在表单下方看到“欢迎您的姓名”刷新页面以查看更改。您只需单击删除按钮即可从localstorage中删除您的姓名。 所有这些任务都有效。但是,如果访问者没有保存任何名称,或者访问者点击删除按钮,我想显示跨度内的原始文本(亲爱的访问者)。请告诉我该怎么做
答案 0 :(得分:1)
您可以创建一个重置值的新myfunction4()
(尽管您可以找到一个更好的名称):
function myfunction4(){
document.getElementById('recalledtext').innerHTML = "Dear visitor,";
}
您可以在用户点击“删除”时调用它:
function myfunction3() {
localStorage.removeItem('mynumber');
myfunction4();
return '';
}
当保存的名称为空白时,您根本不需要做任何事情。
function myfunction2() {
if(localStorage.getItem('mynumber')!="") {
document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber');
}
}
答案 1 :(得分:0)
我已将代码更改为:
<HTML>
<head>
<script>
function myfunction1(){texttosave = document.getElementById('textline').value ; localStorage.setItem('mynumber', texttosave); } function myfunction2() { if(localStorage.getItem('mynumber')!="") { document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } } function myfunction4(){ document.getElementById('recalledtext').innerHTML = "Dear visitor"; } function myfunction5(){texttosav = document.getElementById('Default').value ; localStorage.setItem('mynumber', texttosav); } function myfunction6(){ textdata = document.getElementById('textline').value ; document.getElementById('recalledtext').innerHTML = textdata; }
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name"/>
<input type="hidden" id="Default"value="Dear Visitor" placeholder="Enter Your Name"/><button id="rememberer" onclick='myfunction1();myfunction6();'>remember text</button> <button id="recaller" onclick='myfunction4();myfunction5();'>Delete Your Name</button>
<br>
Welcome <span id="recalledtext" >Dear Visitor</span>, Refresh the page to see changes
</body>
</HTML>
现在它完美无缺。