阻止冒泡

    xiaoxiao2021-12-13  21

    之前一直对冒泡一知半解 今天就去看了一下

    <body > <div class="content"> 外层div元素 <span>内层span元素</span> </div> <div class="msg"></div> </body>

    比如上面这段代码: 给 span div body 都加上click事件以后 当点击span的时候 却也会触发到div以及body的事件 这种就是冒泡

    $(function(){ $('span').bind("click",function(){ var txt = $(".msg").html()+"<p>内层span元素被击中</p>"; $(".msg").html(txt); }); $('.content').bind("click",function(){ var txt = $(".msg").html()+"<p>外层div元素被击中</p>"; $(".msg").html(txt); }); $('body').bind("click",function(){ var txt = $(".msg").html()+"<p>body元素被击中</p>"; $(".msg").html(txt); }); })

    上面这段就会造成事件冒泡 那要怎么阻止事件冒泡呢 jQuery里面有一个stopPropagation() 就是阻止时间冒泡的方法 前提是我们需要添加一个事件对象 这样可以再事件处理函数的时候访问到

    $('span').bind("click",function(event){ var txt = $(".msg").html()+"<p>内层span元素被击中</p>"; $(".msg").html(txt); event.stopPropagation(); });

    这样以后 就成功地阻止了时间冒泡

    转载请注明原文地址: https://ju.6miu.com/read-950199.html

    最新回复(0)