當我在數組中添加新元素時,它會成功添加,但是當我刷新瀏覽器時,添加的元素會從列表本身中刪除。這是我的代碼片段。在刷新時,數組中新添加的元素從數組列表本身中刪除
<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,網絡存儲等。 – nikhil
你能解釋一下網絡存儲是什麼意思。你的意思是本地數據庫? –
當然。添加回答 – nikhil