将数据保存到localstorage并将其显示为innerHTML

问题描述 投票:0回答:1

我已经使用这些代码制作了一个简单的笔记应用程序。它必须通过按下“记住”按钮将文本框值存储到localStorage中。然后显示它,但按下另一个按钮。但它不起作用。

<HTML>

<head>
    <script>
        function myfunction1() { //remember code var
            texttosave = document.getElementById('textline').innerHTML;
            localStorage.setItem('mynumber', texttosave);
        }

        function
        myfunction2() { //recall code
            document.getElementById('recalledtext').innerHTML =
                localStorage.getItem('mynumber');
        }
    </script>
</head>

<body>
    <input type="text" id="textline" />
    <button id="rememberer" onclick='myfunction1()'>remember text</button>
    <button id="recaller" onclick='myfunction2()'>recall text </button>
    <p id="recalledtext">Loading</p>
</body>

</HTML>
javascript html5 stack-overflow angular2-localstorage
1个回答
0
投票

当您输入文本时,qazxsw poi元素qazxsw poi属性不会更改。要查看当前输入到输入框的内容,必须使用其<input>属性。

因此

.innerHTML

需要成为

.value

那应该这样做。

您稍后也会链接到您的测试网站。那里的代码

texttosave = document.getElementById('textline').innerHTML ;

但这使得texttosave = document.getElementById('textline').value ; 成为评论的一部分。你需要写

function myfunction1(){ //remember code texttosave = ..........

现在你把texttosave = ..........放在一个单独的行上,所以它不被认为是评论的一部分。

或者,如果您不想插入换行符以保持代码简洁,请删除注释(function myfunction1(){ //remember code texttosave = .......... texttosave = ......),然后您可以将它们保持在同一行。

另一种方法是将单行注释(例如//remember code)替换为您在同一行关闭的多行注释(即//recall code

© www.soinside.com 2019 - 2024. All rights reserved.