Let me first talk about the function I want to achieve, which is to click on a li tag in a ul to remove the currently clicked li.
But after trying it again and again, I couldn't achieve the effect I wanted.
The current problem is as follows
How to use a more direct method to obtain the li subscript of the current click? The subscript obtained by the for loop was obtained from Baidu.
Remove can be used, but it is not removed according to the li I clicked. For example, if I click 2, it will delete 3 or 4. I don’t know if it is if(e.target == children[i]) here Wrong judgment
Clicking it once has no effect. Click it for the second time to execute removeChild.
HTML structure
<ul id="box">
<li id="one" class="oneclass" data="2017">0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
JS code
document.getElementById("box").addEventListener("click",function(e) {
if(e.target && e.target.nodeName == "LI") {
var children = this.children; //获取ul里面的所有li元素集合
for(var i=0;i<children.length;i++){
if(e.target == children[i]) { //对比目标元素和li集合元素
//alert("目标元素的下标为:" + i); //输出目标元素的下标
document.getElementById(e.target.parentNode.id).removeChild(document.getElementById(e.target.parentNode.id).childNodes[i]);
return;
}
}
}
});