繁体   English   中英

如何通过单击从 JavaScript 的列表中删除项目?

[英]How can i delete items from a list in JavaScript by clicking?

我正在尝试制作购物清单,我希望添加和删除单个项目。 如何才能做到这一点?

 function getValue() { var val = document.getElementById("itemList").value; var list = document.getElementById("demo"); var element = document.createElement("li"); var addList = document.createTextNode(val); element.appendChild(addList); list.prepend(element); }
 <html> <head> <title> Common List </title> </head> <body> <form> <input type="text" id="itemList"> <button type="button" onclick="getValue()">add to list</button> <ul id="demo"></ul> </form> </body> </html>

添加时向元素添加事件侦听器。 这可以使用remove()方法将其从列表中删除。

 function getValue() { var val = document.getElementById("itemList").value; var list = document.getElementById("demo"); var element = document.createElement("li"); var addList = document.createTextNode(val); element.appendChild(addList); element.addEventListener("click", function() { if (confirm(`Do you really want to remove ${this.innerText}`)) { this.remove(); } }); list.prepend(element); }
 <html> <head> <title> Common List </title> </head> <body> <form> <input type="text" id="itemList"> <button type="button" onclick="getValue()">add to list</button> <ul id="demo"></ul> </form> </body> </html>

暂无
暂无

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

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