每当我在数组中添加新元素时,它都会成功添加,但是当我刷新浏览器时,添加的元素将从列表本身中删除。这是我的代码片段。
<html>
<label>Enter an New item to add in Stock</label> <br> </br>
<input type="text" name=" itemName" id="addItemInStock><br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()" return="false">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
<option value="" disabled selected style="display: block;">Stock Items</option>
</select>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");
function addToStock(){
if ((newItem.value) === ""){
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
document.getElementById("errorMsg").style.display = "block";
}
else{
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
document.getElementById("showList").innerHTML = fruits;
clearAndShow();
}
var sel = document.getElementById("showInDropDown");
document.getElementById("showInDropDown").innerHTML = "";
for (var i = 0; i < fruits.length; i++)
{
var opt = document.createElement('option');
sel.appendChild(opt);
}
}
function clearAndShow(){
newItem.value = "";
}
</script>
</html>
最佳答案
因为刷新时,页面会重新绘制。如果您需要保存列表,那么您需要使用一些网络存储,即 localStorage、网络存储等。
以下是localStorage的一个简单用例
更新自
var fruits = ["Banana", "Orange", "Apple", "Mango"];
至
var fruitsfromLS = localStorage.getItem("fruits");
var fruits = fruitsfromLS ? JSON.parse(fruitsfromLS) : ["Banana", "Orange", "Apple", "Mango"];
并更新
fruits.push(newItem.value);
至
fruits.push(newItem.value);
localStorage.setItem("fruits", JSON.stringify(fruits));
仅供引用,localStorage
关于javascript - 刷新时,数组中新添加的元素将从数组列表本身中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647778/