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

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

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);

});

});

### 如何在 `swipeBtnClick` 方法中同时传递 `btnOptions` 和上层 `item` 在 Vue.js 中,可以通过绑定事件并利用 JavaScript 的闭包特性或者显式传递参数的方式解决此问题。以下是具体实现方式: #### 使用 `$event` 参数 当需要在一个事件处理器中传递多个参数时,可以借助 `$event` 来捕获原生 DOM 事件或其他数据。 假设结构如下: ```html <template> <div v-for="(item, index) in items" :key="index"> <button @click="swipeBtnClick(item, btnOptions)">Click Me</button> </div> </template> <script> export default { data() { return { items: [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], btnOptions: { label: 'Delete', color: 'red' } }; }, methods: { swipeBtnClick(item, options) { console.log('Clicked item:', item); console.log('Button options:', options); } } }; </script> ``` 在此示例中,`@click="swipeBtnClick(item, btnOptions)"` 将当前循环的 `item` 对象以及固定的 `btnOptions` 同时作为参数传递给 `swipeBtnClick` 方法[^1]。 --- #### 如果涉及动态生成按钮或复杂场景 对于更复杂的场景(例如动态生成按钮),可能需要通过嵌套作用域来确保上下文正确传递。以下是一个例子: ```html <template> <ul> <li v-for="(item, index) in items" :key="index"> {{ item.name }} <!-- 动态生成按钮 --> <button v-for="option in btnOptions" :key="option.label" @click="swipeBtnClick($event, item, option)"> {{ option.label }} </button> </li> </ul> </template> <script> export default { data() { return { items: [ { id: 1, name: 'Item A' }, { id: 2, name: 'Item B' } ], btnOptions: [ { label: 'Edit', action: 'edit' }, { label: 'Delete', action: 'delete' } ] }; }, methods: { swipeBtnClick(event, item, option) { console.log('Event details:', event.target); // 获取触发事件的目标元素 console.log('Current Item:', item); // 当前项的数据 console.log('Selected Option:', option); // 按钮选项的具体配置 } } }; </script> ``` 在这个例子中,`$event` 被用来捕获原始 DOM 事件对象,而 `item` 和 `option` 则分别表示列表中的项目和按钮的特定属性[^2]。 --- #### 配合 API 请求的完整案例 如果还需要进一步调用外部接口,则可以在方法内部完成逻辑封装。例如: ```html <template> <div> <h1>User List</h1> <ul> <li v-for="(user, index) in users" :key="index"> {{ user.name }} ({{ user.email }}) <button @click="handleAction(user, actions.delete)"> Delete </button> <button @click="handleAction(user, actions.edit)"> Edit </button> </li> </ul> </div> </template> <script> import api from './api'; export default { data() { return { users: [ { id: 1, name: 'Alice', email: 'alice@example.com' }, { id: 2, name: 'Bob', email: 'bob@example.com' } ], actions: { delete: { label: 'Delete', method: 'DELETE' }, edit: { label: 'Edit', method: 'PUT' } } }; }, methods: { handleAction(user, action) { const url = `/users/${user.id}`; const config = { method: action.method }; api.request(url, config).then(() => { if (action.method === 'DELETE') { this.users = this.users.filter(u => u.id !== user.id); } }); } } }; </script> ``` 此处展示了如何将用户操作映射到具体的 HTTP 请求,并根据返回结果更新状态[^3]。 --- ### 总结 以上三种方案均能有效满足需求,开发者可以根据实际业务场景灵活选用。无论是简单的静态页面还是复杂的交互逻辑,Vue 提供了强大的工具链支持高效开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值