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

How to delete an <li> from list with javascript

我想做的是使用 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 来做这件事。 谢谢! :)

基于您的标记:

<ul id ="shape-list" class="list-group mt-3 mb-3"> 
<li>Link: url.com <i class="delete-icon fas fa-trash-alt"></i> </li> 
</ul>

您可以简单地使用 Node 方法 removeChild。这是假设 i 标签是您活动中的目标。

 target.parentNode.parentNode.removeChild(target.parentNode);

在您的代码中:

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

    target.parentNode.parentNode.removeChild(target.parentNode);
};

我不知道你的列表是什么样的,但你应该可以相应地采用它。

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 本身的 委托侦听器 ,请开始:

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>