简体   繁体   中英

How to add user prompt input to an array permenantly

So I'm trying to add a prompt which asks the user what they would like to add to an array. However, whenever I refresh the page, it gets deleted like it is only in local storage. I would like to add this to the actual code so it gets displayed permanently within the page. Here is the relavent code:

<html>
<body>
<div class="ann" id="shadowbox">
    <h4>Latest Announcements</h4>
    <ul id="myUl"></ul>
  </div>
<button onclick="fc()">populate</button>

<script>
var announcements = ["test",]

for (i = 0; i < announcements.length; i++) {
  var li = document.createElement("li");
  var text = document.createTextNode(announcements[i]);
  li.appendChild(text);
  document.getElementById("myUl").appendChild(li);
}

    function fc() {
    var asdkz = prompt("What would you like to add?")
    announcements.push(asdkz);
    }
</script>

You need to use localStorage to save the content of the array after refresh. Here is the solution with some modification:

<html>
<body>
<div class="ann" id="shadowbox">
    <h4>Latest Announcements</h4>
    <ul id="myUl"></ul>
  </div>
<button onclick="fc()">populate</button>

<script>
var announcements = (localStorage.getItem("list")) ? localStorage.getItem("list").split(",") : ["test"]
updateList();
function updateList(){
     document.getElementById("myUl").innerHTML = "";
     for (i = 0; i < announcements.length; i++) {
          var li = document.createElement("li");
          var text = document.createTextNode(announcements[i]);
          li.appendChild(text);
          document.getElementById("myUl").appendChild(li);
     }
}

function fc() {
    var asdkz = prompt("What would you like to add?")
    announcements.push(asdkz);
    localStorage.setItem("list",announcements);
    updateList();
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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