如何在点击事件中从JavaScript数组中移除对象?
解决方案:点击按钮移除列表项并同步更新数组
要实现点击按钮移除对应列表项,同时同步删除vacationList数组里的对应数据,核心是给每个列表项绑定它在数组中的索引,确保删除操作能精准匹配DOM元素和数组数据。
修改后的完整代码如下:
let vacationList = []; $('#add').click(function(e){ e.preventDefault(); let vacationHours = $('#vacationHours').val(); let vacationDates = document.querySelector("#vacationDates").value; const li = document.createElement("li"); li.innerText = vacationHours + "h - " + vacationDates; // 给列表项绑定数组索引,push前的数组长度就是新元素的索引 li.dataset.index = vacationList.length; const button = document.createElement("button"); button.className = "fa fa-minus-circle"; const ul = document.querySelector(".list"); ul.appendChild(li); li.appendChild(button); button.addEventListener('click', (e) => { e.preventDefault(); // 获取当前按钮所在的列表项 const currentLi = e.target.parentElement; // 从DOM中移除该列表项 currentLi.remove(); // 解析列表项绑定的数组索引 const index = parseInt(currentLi.dataset.index); // 从数组中删除对应元素 vacationList.splice(index, 1); // 可选:删除后更新剩余列表项的索引,避免后续操作错位 document.querySelectorAll(".list li").forEach((item, idx) => { item.dataset.index = idx; }); }); vacationList.push({vacationHours: Number(vacationHours), vacationDates: vacationDates}); });
关键细节说明
- 绑定数组索引:创建
<li>时,用li.dataset.index = vacationList.length存储新元素的数组索引(push操作前的数组长度就是新元素插入后的索引值)。 - 移除DOM元素:通过
e.target.parentElement获取按钮的父元素<li>,直接调用remove()即可删除页面上的列表项。 - 删除数组元素:用
splice(index, 1)删除数组中对应位置的元素,第一个参数是索引,第二个参数1表示只删除1个元素(splice会直接修改原数组)。 - 索引同步更新:如果后续还要对数组或列表项进行操作,需要遍历剩余列表项更新它们的
data-index属性,防止索引错位导致删除错误。
内容的提问来源于stack exchange,提问作者dufva
相关产品推荐
相关产品推荐

