只需使用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>
<input type="checkbox" value="1" name="todo[]">
<span class="centerSpan" style="text-decoration: none;">abc</span>
<button class="rightButton">X</button>
</li>
答案 0 :(得分:1)
从目标(按钮,在这种情况下)调用closest()以获取对li元素的引用
var li = e.target.closest('li');
然后使用Array.from()并传递children HTMLCollection
获取您孩子的孩子的数组引用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()
等方法进行填充