gpt4 book ai didi

Javascript:如何删除绑定(bind)到删除按钮的元素(动态)

转载 作者:行者123 更新时间:2023-11-29 19:15:21 26 4
gpt4 key购买 nike

我目前正在使用添加按钮将文本框中的输入添加到列表中。我还将一个按钮绑定(bind)到每个列表元素,然后将它们附加到无序列表。如何移除对应移除按钮的元素onclick?仅限纯 JavaScript。

window.onload = function() {

var elements = [];
var textInput;

document.getElementById("addButton").onclick = function() {

textInput = document.getElementById("inputBox").value;

if (textInput == "") {
alert("Make sure your input is not empty!");
} else {


var liNode = document.createElement('li');
var btnNode = document.createElement('button');

var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);

var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);

document.getElementById("myInputList").appendChild(liNode);
}

}


function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<!DOCTYPE html>
<html>

<body>

<head>
<script src="func.js"></script>
</head>

<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>

</body>

</html>

最佳答案

Use addEventListener to register click event over created button.

使用.remove() , 从它所属的树中删除对象。

试试这个:

window.onload = function() {
var elements = [];
document.getElementById("addButton").onclick = function() {
var textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
btnNode.addEventListener('click', removeHandler);
}
}

function removeHandler() {
this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
}

function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>

关于Javascript:如何删除绑定(bind)到删除按钮的元素(动态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com