• 你真的了解浏览器事件冒泡吗


    先上一段代码

    <div id="test">
        <div class="child">
            click
        </div>
    </div>
    

      

    <script>
       document.addEventListener('click', function (e) {
           if(e.target.classList.contains('child')){
               console.log('child')
           }
           if(e.target.id==='test'){
               console.log('test')
           }
           if(e.target.tagName === 'HTML'){
               console.log('html')
           }
       }, false)
    </script>
    

      想一下,当点击click的时候,控制台会打印出什么?

    一开始我认为是顺序打印出child,test,html。但是实际上只打印了child。理解不深啊。

    实际上一个监听事件的处理函数handle的e.target只有一个,就是指向被点击最具体的那个节点。所以这里的e.target就是child这个节点。故后面两个if是不成立的。

    如何想实现上面的功能呢,具体代码

    <script>
    document.addEventListener('click', function(e) {
    console.log(e.path,"e.path")
    var target = e.target;
    while (target) {
    if (target.classList && target.classList.contains('child')) {
    console.log('child')
    }
    if (target.id === 'test') {
    console.log('test')
    }
    if (target.tagName === 'HTML') {
    console.log('html')
    }
    target = target.parentNode;
    }
    }, false)
    </script>

      逐层查找这些父节点。这样就可以顺序打印出child,test,html了。

  • 相关阅读:
    Docker大会的新福利:LinuxKit 和 Moby 开源项目
    NS3
    (OK) NS3
    MPTCP
    Utilizing multi-core processors in NS-2
    (OK) Fedora 24
    error compiling gcc: undefined reference to libc_name_p
    gccxml
    NS3
    NS3
  • 原文地址:https://www.cnblogs.com/childsplay/p/4758396.html
Copyright © 2020-2023  润新知