只是使用javascript,需要通过以下监听器获取被点击的li的索引:
var ulList = document.getElementById('todo-list');
ulList.addEventListener('click', function(e){
if( e.target.nodeName == "BUTTON") {
//IS THERE A WAY INSIDE HERE TO GET THE INDEX OF THE li clicked
e.target.parentNode.remove();
}
});
每个 li 看起来像:
<li>
<input type="checkbox" value="1" name="todo[]">
<span class="centerSpan" style="text-decoration: none;">abc</span>
<button class="rightButton">X</button>
</li>
最佳答案
从目标(在本例中为按钮)调用 closest()获取对您的 li 元素的引用
var li = e.target.closest('li');
然后使用 Array.from() 获取您的 UL 的 child 的数组引用并传入 children HTML集合
var nodes = Array.from( ulList.children );
//or if you want to not depend on externally defined variables
var nodes = Array.from( li.closest('ul').children );
最后调用indexOf()获取索引
var index = nodes.indexOf( li );
如果想要支持旧浏览器,则需要为 Array.from() 等方法填充代码
关于javascript - 如何获取在javascript中点击的li的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48977577/