猿问

动态删除列表元素

我计划为待办事项列表编写JavaScript代码,以将元素动态添加到无序列表以及每个元素的删除按钮。当用户单击“删除”按钮时,我想删除相应的列表元素。如何动态删除所述列表元素


var button = document.querySelector("button");

var input = document.querySelector("input");

var ul = document.querySelector("ul");

button.addEventListener("click",function(){

    if((input.value.length)>0&&(input.value.includes("by")===true))

    {

        var li= document.createElement("li");

        li.appendChild(document.createTextNode(input.value + " "));

        ul.appendChild(li);

        input.value="";

        var nb= document.createElement("button");

        nb.appendChild(document.createTextNode("REMOVE"));

        li.appendChild(nb);

    }

    else if(input.value.includes("by")===false)

    {

        alert("Make Sure You Adhere to the Defined Format");

    }

});


慕码人8056858
浏览 165回答 1
1回答

慕码人2483693

您可以添加一个onclick处理程序,然后单击按钮获取parentNode并使用remove将其删除var button = document.querySelector("button");var input = document.querySelector("input");var ul = document.querySelector("ul");button.addEventListener("click", function() {&nbsp; if ((input.value.length) > 0 && (input.value.includes("by") === true)) {&nbsp; &nbsp; var li = document.createElement("li");&nbsp; &nbsp; li.appendChild(document.createTextNode(input.value + " "));&nbsp; &nbsp; ul.appendChild(li);&nbsp; &nbsp; input.value = "";&nbsp; &nbsp; var nb = document.createElement("button");&nbsp; &nbsp; //nb.classList.add('remove');&nbsp; &nbsp; nb.onclick = removeThis; // added onclick handler&nbsp; &nbsp; nb.appendChild(document.createTextNode("REMOVE"));&nbsp; &nbsp; li.appendChild(nb);&nbsp; } else if (input.value.includes("by") === false) {&nbsp; &nbsp; alert("Make Sure You Adhere to the Defined Format");&nbsp; }});function removeThis() {&nbsp; this.parentNode.remove();}<ul></ul><input type='text'><button type='button'>Add</button>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答