可以't让localStorage在刷新时显示输出

Can't get localStorage to display output on refresh

本文关键字:刷新 显示 输出 localStorage 可以      更新时间:2023-09-26

这是一个练习练习(在进入训练营之前),是用户输入的最喜欢的东西的列表。LocalStorage的工作原理是正确保存和删除,直到刷新时,整个列表都会消失。但在另一个条目之后,整个列表就会加载;刷新后它就不会再出现了。就我的一生而言,我不明白为什么。

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-9 stuff">
      <h3><i>Enter in a favorite thing, then hit the button</i></h3>
<!-- form -->
      <form id="the-form">
        <input id="list-input" type="text" placeholder="sexy time" size="40">
        <button class="btn btn-warning" type="submit">Submit</button>
        <hr>
      </form>
    </div> <!-- /col-sm-12 -->
  </div> <!-- /row -->
<!-- results -->
  <div class="row">
    <div id="show" class="col-sm-7">
      <h3 class="fav-things">My most favoritest things</h3>
      <ul id="list-items">
      </ul>
    </div>
  </div> <!-- /row -->
</div> <!-- /container -->

jQuery

$(document).ready(function() {
    $("#list-items").html(localStorage.getItem("listItems")); // refresh not working
    $("#the-form").submit(function(event) {
        event.preventDefault();
        var item = $("#list-input").val();
        if (item) {
            $("#list-items").append("<li>" + item + "<a href='#' class='delete'>x</a><hr></li>");
            $("#show").show();
        }
        localStorage.setItem("listItems", $("#list-items").html()); // saves input to localStorage
        $("#list-input").val("");  // removes value from input
    });
  // Remove List item
    $(document).on("click", ".delete", function() { // .on() to work with dynamic element <li>
        $(this).parent().slideUp(300, function() { // grabbing the parent of the x that was clicked on
            $(this).remove();  // removing the parent of the clicked on x
            localStorage.setItem("listItems", $("#list-items").html());  // saves input to localStorage
        });
    });
});

CSS-我忘了添加CSS,它的结果最初用#show{display:none;}隐藏

body {
  padding-top: 70px;
}
.stuff {
  background-color: #ffe5ff;
  border: 1px solid #ffe5ff;
  border-radius: 8px;
  margin-bottom: 10px;
}
#list-input {
  padding-left: 5px;
}
#show {
  display: none;
  background-color: #e5ffff;
  border: 1px solid #99ddff;
  border-radius: 8px;
}
.delete {
  float: right;
  padding: 10px;
  text-decoration: none;
  color: black;
}
hr {
  width: 80%;
}
.fav-things {
  padding-bottom: 5px;
  border-bottom: 2px solid #d9d9d9;
}

file:///Users/Padawan/Dropbox/folder/folder_2/JavaScript/23_JQ_code_review/index‌​.html?#

这就解释了。你需要尝试从一个小型的"网络服务器"上查看你的项目,然后你的浏览器可以连接到"http://localhost"或"http://localhost:1234"(端口号)来查看你的工程。其中一个比较容易设置的是"XAMPP"。你可以四处寻找其他人,其中许多人会比你需要的更复杂。一个合适的谷歌搜索应该是"免费的基本网络服务器"。