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

时间:2018-11-12 19:13:20

标签: 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.

    };

有人可以帮我用香草js而不是jquery做到这一点吗? 谢谢! :)

2 个答案:

答案 0 :(得分:2)

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

const hotel = {
    name: "Grand Hotel",
    location: "Stockholm",
    pricePerNight: 2200,
    roomBooked: 23,
    totalRoom: 223, 
    roomAvailable: function(){
        return this.totalRoom - this.roomBooked;
        
    }   
    };
  
    console.log(hotel.roomAvailable());
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);
})

答案 1 :(得分:1)

基于您的标记:

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