javascript 事件委托

仅作为个人笔记使用,不进行详细说明

参考:https://blog.csdn.net/lszyzs/article/details/106876057

https://zhidao.baidu.com/question/497365658094414364.html

 

删除

<ul>
</ul>
<script>
// 由于是自动在ul标签中生成li标签的
let ul = document.querySelector("ul")
ul.onclick = (event) => {
    if(event.target.nodeName == "LI") {
      ul.removeChild(event.target)
    }
}
</script>

  

获取自动生成标签的下标

    <ul>
    </ul>
    <button>button</button>
    <script>
        let ul = document.querySelector("ul")
        let button = document.querySelector("button")
        button.onclick = function(event) {
            let li = document.createElement("li")
            li.innerHTML = "10"
            ul.appendChild(li)
        }
        ul.onclick = (event) => {
            let lis = document.querySelectorAll("li")
            if (event.target.nodeName == "LI") {
                lis.forEach((item, index) => {
                    if(event.target == item) {
                        console.log(index)
                    }
                })
                // ul.removeChild(event.target)
            }
        }
    </script>

  

posted @ 2021-10-23 14:01  感觉678  阅读(35)  评论(0编辑  收藏  举报