阻止事件冒泡

来源:互联网 发布:流量龙卷风淘宝 编辑:程序博客网 时间:2024/06/06 21:26

事件冒泡指事件在初始DOM上触发,通过DOM树往上在每一级父元素上触发。

阻止事件向上冒泡,一般用return false;但是return false 的实际作用为:

   event.preventDefault();

   event.stopPropagation();

   停止回调函数执行并立即返回。


如果$("div a").click(function(){ return false}),再需要点击div时,$("div").click(function(){})事件不会被触发,此时解决方法为

第一种情况:

("div.post").click(function(){    $("div.post .content").hide();          // hide all content    $(this).children(".content").show();    // show this one});

$("div.post a").click(function(e) {    var href = $(this).attr("href");    $(this).next().load(href);    e.preventDefault();});
第二种情况:

$("div.post").click(function(){    // do something});$("div.post a").click(function(e){    // 浏览器跳转到新页面(默认行为)    // 但阻止事件冒泡,即不会执行$("div.post").click()    e.stopPropagation();});

另外:return false和live/delegate事件不要混用。


event.stopPropagation()用于阻止事件冒泡,jQuery中还有另一个函数:event.stopImmediatePropagation(),它用于阻止一个事件的继续执行,即使当前对象上还绑定了其他处理函数:

$("div a").click(function(){    // do something});$("div a").click(function(e){    // stop immediate propagation    e.stopImmediatePropagation();});



return false ----》 在事件的处理中,可以阻止默认事件和冒泡事件。 
2:event.preventDefault()---》在事件的处理中,可以阻止默认事件但是允许冒泡事件的发生。 
3:event.stopPropagation()---》在事件的处理中,可以阻止冒泡但是允许默认事件的发生。

0 0
原创粉丝点击