2016-11-17 54 views
1

當我在數組中添加新元素時,它會成功添加,但是當我刷新瀏覽器時,添加的元素會從列表本身中刪除。這是我的代碼片段。在刷新時,數組中新添加的元素從數組列表本身中刪除

<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> 
+0

由於刷新頁面被重新繪製。如果你需要保存列表,那麼你需要使用一些網絡存儲,即localStorage,網絡存儲等。 – nikhil

+0

你能解釋一下網絡存儲是什麼意思。你的意思是本地數據庫? –

+0

當然。添加回答 – nikhil

回答

1

由於刷新頁面被重新繪製。如果您需要保存列表,然後你需要使用一些網絡存儲即本地存儲,網絡存儲等

以下是的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

+0

抱歉,但它似乎並沒有在我的情況下工作.. –

+0

@Prasad_Joshi - 您的id爲addItemInStock的html元素缺少引號。這裏它也適用於你的情況 - http://plnkr.co/edit/tYQZyMrxvCDaoEswpHMs?p=preview – nikhil

+0

啊它適用於chrome,但不適用於Mozilla瀏覽器版本49.0.2 ..感謝您的幫助。 –