我在數組中添加了新元素,並試圖將所有這些元素動態地設置爲java腳本中的選擇框,但是在瀏覽器的每次刷新選擇框中都會變空但是,在瀏覽器刷新時,框外顯示的列表不會更改。數組元素沒有顯示在javascript中的選擇框中
<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()">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
<option disabled selected style="display: block;">Stock Items</option>
</select>
<script>
var fruitsfromLS = localStorage.getItem("fruits");
var fruits = fruitsfromLS ? JSON.parse(fruitsfromLS) : ["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);
//this is added extra
// localStorage.setItem("fruits", JSON.stringify(fruits));
var StoredFruits = localStorage.setItem("fruits", JSON.stringify(fruits));
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');
opt.innerHTML = fruits[i];
opt.value = fruits[i];
sel.appendChild(opt);
}
}
function clearAndShow() {
newItem.value = "";
}
</script>
</html>
由於內容是動態添加的,因此它們往往會在每次刷新頁面時丟失其值。這是正常的行爲。 –
我們如何實現將這些數組元素動態地存儲在選擇框中。 –
你應該填寫它在evry頁面加載然後 –