简体   繁体   English

尝试从数组中删除元素并使数组在Javascript中的网页上“刷新”

[英]Trying to remove an element from array AND have the array “refresh” on the webpage in Javascript

Javascript newbie here. Javascript新手在这里。 I made an javascript application that adds and removes item elements from a list array. 我制作了一个JavaScript应用程序,用于从列表数组添加和删除项目元素。 The add functions. 添加功能。 The delete doesn't function. 删除无效。 I think maybe the item elements are being deleted from the array, however; 我认为也许item元素正在从数组中删除。 the array isn't being "refreshed" on the webpage. 阵列未在网页上“刷新”。 Anybody know how to make it work? 有人知道如何使其工作吗? Thanks, Eliza 谢谢,伊丽莎

HTML: HTML:

<p>GROCERY LIST-INATOR</p>
<p>Click the button to add an item to grocery list.</p>

<button onclick="addItem()">Add item</button>
<button onclick="deleteItem()">Delete item</button>

<p id="list"></p>

JS: JS:

var list = [];

function addItem (){
    var name = prompt("Enter item name:");
    list.push(name);
    var today = Date();
    var string = "Created on " + today + "<br>" + " My Grocery List: <br>";
    for (var key in list){
        string += "- " + list[key] + "<br>";
    }
    document.getElementById("list").innerHTML = string;
};

function deleteItem (){
    var item = prompt("Enter item name:");
    for(var i = list.length - 1; i >= 0; i--) {
        if(list[i] === item) {
        list.splice(i, 1);
    }
}
   document.getElementById("list").innerHTML = string;
};

http://jsfiddle.net/elizaway/9d0376t1/ http://jsfiddle.net/elizaway/9d0376t1/

You are not updating string variable in your second function. 您没有在第二个函数中更新字符串变量。 Try add you string related code in second function before use string variable and you are done.. 尝试在使用字符串变量之前在第二个函数中添加与字符串相关的代码,然后完成。

var string = "Created on " + today + "<br>" + " My Grocery List: <br>"; 
for (var key in list)
  { 
    string += "- " + list[key] + "<br>"; 
   }

Above code come between for loop and this code. 上面的代码介于for循环和此代码之间。

document.getElementById("list").innerHTML = string;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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