javascript - Issues about JS event delegation operation ul li tag
巴扎黑
巴扎黑 2017-06-28 09:27:49
0
2
848

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

  1. 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.

  2. 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

  3. 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;
            }
        }
    }
});
巴扎黑
巴扎黑

reply all(2)
習慣沉默
document.querySelector('#box').addEventListener('click',function(e){
    if(e.target.nodeName=="LI"){
        e.target.parentNode.removeChild(e.target);
    }
});
巴扎黑
<!DOCTYPE HTML>
<html>
<ul id="box">
    <li id="one" class="oneclass" data="2017" onclick="removeli(this);">0</li>
    <li onclick="removeli(this);">1</li>
    <li onclick="removeli(this);">2</li>
    <li onclick="removeli(this);">3</li>
    <li onclick="removeli(this);">4</li>
</ul>

<script>
function removeli(node){node.parentNode.removeChild(node);}
</script>
</html>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template