0

我制作了这段代码来将表单数据保存到本地存储

<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>

如果您输入您的姓名并单击保存按钮,它会将您的姓名保存到本地存储中。然后,如果您刷新页面,您将在表单下方看到“欢迎‘您的姓名’刷新页面以查看更改”。您可以通过单击删除按钮从本地存储中删除您的姓名。所有这些任务都在工作。但是,如果访问者没有保存任何名称,或者访问者单击删除按钮,我想显示跨度内的原始文本(亲爱的访问者,)。请告诉我该怎么做

4

2 回答 2

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'); 
    }
}
于 2017-08-06T05:08:06.577 回答
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>

现在它完美地工作了。

于 2017-08-06T07:16:34.183 回答