简体   繁体   English

如何在html上显示本地存储

[英]How to display local storage on html

im trying to display the output of local storage我试图显示本地存储的输出

function addSampleNotes() {

    localStorage. setItem( '2020-09-28 13:35:00', 'Call Tony about blog code');
    localStorage. setItem( '2020-10-02 07:00:00', 'Buy eggs');
    localStorage. setItem( '2020-10-14 16:21:00', 'Hang out the washing');
}

addSampleNotes();

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.getItem( localStorage.key( i ) ) );
}

This manages to come up in the console perfectly however i want it to display on my html page这设法完美地出现在控制台中,但是我希望它显示在我的 html 页面上

var output = document.getElementById("output");

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  output.innerHTML = ( localStorage.getItem( localStorage.key( i ) ) );
}

tried adding something like this but i get null errors.尝试添加这样的东西,但我得到空错误。 How can i display my local storage on the html?如何在 html 上显示我的本地存储?

HTML HTML

<body>
    
    <fieldset>
       <legend>My Tunings</legend>
       <div id="output"></div>
    </fieldset>
<script type="text/javascript" src="js.js">
    </script>
    
  </body>

error is错误是

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at js.js:14```


I suggest you put every item into its own element.我建议您将每个项目放入其自己的元素中。 For example paragraphs, or in your case an unordered list ul would be best.例如段落,或者在你的情况下无序列表ul会是最好的。

Like so:像这样:

for (var i = 0, len = localStorage.length; i < len; ++i) {
    var element = document.createElement("p")
    element.textContent = localStorage.getItem(localStorage.key(i))
    output.appendChild(element)
}

Prefer textContent instead of innerHTML or outerHTML if you are not setting HTML, as it is a possible security threat.如果您不设置 HTML,则首选textContent而不是innerHTMLouterHTML ,因为它可能存在安全威胁。

The error you posted in your edit, tells you that output variable on which you are trying to operate is null.您在编辑中发布的错误告诉您,您尝试操作的output变量为空。 Make sure that you do not have a syntax error and that you run JavaScript after HTML is loaded.确保您没有语法错误,并且在加载 HTML 后运行 JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM