阻止执行父事件处理程序 [英] Prevent execution of parent event handler

查看:30
本文介绍了阻止执行父事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵 div 树:

<div id="b" onclick="func"><div id="c" onclick="func">

当在 div 上单击时,它的子项将不可见 - 即单击a"将使b"和c"不可见.

function func{如果 ($(childId).hasClass("visible")){$(childId).removeClass("可见");$(childId).addClass("invisible");}

问题是:点击b"会调用a"的点击并使b"和c"不可见.如何使用 jQuery 禁用对a"的点击?

谢谢

解决方案

您可以为子级添加处理程序,以防止单击事件向上传播:

函数处理程序(事件){event.stopPropagation();//现在做你的事}$('#a').add('#b').click(handler);

这种方式对 '#b' 的点击不会传播到 '#a'.点击 '#c' 也不会转到 '#b',因此也不会转到 '#a'.

I have a tree of divs:

<div id="a" onclick="func">
    <div id="b" onclick="func">
         <div id="c" onclick="func">
         </div>
    </div>
</div>

When a click is made on a div it makes it's children invisible - ie click on "a" will turn "b" and "c" invisible.

function func{
   if ($(childId).hasClass("visible")){
    $(childId).removeClass("visible");
    $(childId).addClass("invisible");
}

The problem is: a click on "b" will call "a"'s click and make "b" and "c" invisible. How do I disable the click on "a" using jQuery?

thanks

解决方案

You can add a handler for the child that will prevent the click event from propagating up:

function handler(event) {
    event.stopPropagation();
    // now do your stuff        
}
$('#a').add('#b').click(handler);

This way clicks to '#b' will not propagate to '#a'. Neither will clicks to '#c' go to '#b', and hence not to '#a'.

这篇关于阻止执行父事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆