html li onclick,javascript - Remove clicked <li> onclick - Stack Overflow

本文介绍了一种使用纯 JavaScript 和 jQuery 实现动态列表项添加与移除的方法。通过监听点击事件,可以实现在用户界面上动态添加和删除列表项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UPDATE

Plain JS delegation

Add the eventListener to the UL to delegate the click even on dynamically inserted LIs:

document.getElementById("ul").addEventListener("click",function(e) {

var tgt = e.target;

if (tgt.tagName.toUpperCase() == "LI") {

tgt.parentNode.removeChild(tgt); // or tgt.remove();

}

});

jQuery delegation

$(function() {

$("#submitButton").on("click",function() {

var text = $("#item").val(); //getting value of text input element

var li = $('

').text(text)

$("#ul").prepend(li);

});

$("#ul").on("click","li",function() {

$(this).remove();

});

});

Original answer

Since you did not mention jQuery

var listItems = document.getElementsByTagName("li"); // or document.querySelectorAll("li");

for (var i = 0; i < listItems.length; i++) {

listItems[i].onclick = function() {this.parentNode.removeChild(this);}

}

you may want to wrap that in

window.onload=function() { // or addEventListener

// do stuff to the DOM here

}

Re-reading the question I think you also want to add that to the dynamic LIs

li.innerHTML = text; //inserting text into newly created

element

li.onclick = function() {

this.parentNode.removeChild(this);

// or this.remove(); if supported

}

Here is the complete code as I expect you meant to code it

window.onload=function() {

var button = document.getElementById("submitButton");

button.onclick = addItem;

}

function addItem() {

var textInput = document.getElementById("item"); //getting text input

var text = textInput.value; //getting value of text input element

var ul = document.getElementById("ul"); //getting element

  • to add element to

var li = document.createElement("li"); //creating li element to add

li.innerHTML = text; //inserting text into newly created

element

li.onclick = function() {

this.parentNode.removeChild(this);

// or this.remove(); if supported

}

if (ul.childElementCount == 0) { //using if/else statement to add items to top of list

ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item

}

else {

ul.insertBefore(li, ul.firstChild);

}

}

In case you want to use jQuery, the whole thing gets somewhat simpler

$(function() {

$("#submitButton").on("click",function() {

var text = $("#item").val(); //getting value of text input element

var li = $('

')

.text(text)

.on("click",function() { $(this).remove()});

$("#ul").prepend(li);

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值