javascript - 如何使用 javascript 从列表中删除 <li>

标签 javascript html dom html-lists dom-manipulation

我想做的是使用 javscript 删除用户从 DOM 中单击的任何列表项。这是我的代码:

// Delete shape from ul event
    shapeList.onclick = function (event) {
        var shapesArray = shapesCtrl.getShapesArray();
        var target = event.target; // Getting which <li> was clicked
        var id = target.parentNode.id; // Getting the value of the li that was clicked
        canvasCtrl.deleteShape(shapesArray, id); // Deleting the targeted element from the array 

        var li = shapeList.childNodes;

        // Above i remove the object that the corresponds with the li the user clicked on but i cant remove the actual li itself... Ive tried to use li[id].remove() but it just keeps removing the 1st li even though the id might point to the last item for example.

    };

任何人都可以帮我用 vanilla js 而不是 jquery 来做到这一点吗? 谢谢! :)

最佳答案

我不知道您的列表是什么样的,但您应该能够相应地采用它。

const lis = [...document.querySelectorAll('.this-list li')];

for (const li of lis) {
  li.addEventListener('click', function() {
    this.parentNode.removeChild(this);
  })
}
<ul class="this-list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

如果您更喜欢 ul 本身的委托(delegate)监听器,那么您可以这样做:

const ul = document.querySelector('.this-list');

ul.addEventListener('click', function(e) {
  this.removeChild(e.target);
})
<ul class="this-list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

这样做的优点是它也适用于动态创建的列表项:

const ul = document.querySelector('.this-list');

for (let i=0; i<5; i++) {
  let li = document.createElement('li');
  li.textContent = `Item ${i+1}`;
  ul.appendChild(li);
}

ul.addEventListener('click', function(e) {
  this.removeChild(e.target);
})
<ul class="this-list"></ul>

关于javascript - 如何使用 javascript 从列表中删除 <li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53268641/

相关文章:

html - 当祖先显示 : flex 时,IE11 表格布局会中断

HTML 按钮在新标签页中打开链接

javascript - 使用 document.getElementById 替换 insideHTML 时出现意外行为

javascript - 如何将特定文本插入CKEditor图像/链接对话框URL输入字段?

javascript - 是否可以修改 Location 对象的现有属性,例如 "location.href"?

javascript - 用javascript中修改后的值替换html内容

javascript - 通过 Ajax 将页面加载到 div 返回错误

javascript - 如何检测一个空的 div,然后使用 JS 或 css 插入一个 html 按钮

javascript - jQuery 属性操作的不一致

PHP 获取 DOMNode 的 XPath