我想做的是使用 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/