将多个事件处理程序绑定到一个元素时的优先级 [英] Priority when more than one event handler is bound to an element

查看:170
本文介绍了将多个事件处理程序绑定到一个元素时的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个元素绑定了多个事件处理程序时,如何确定首先触发哪个事件处理程序?

When more than one event handler is bound to an element, how is it determined which one is triggered first?

<script> 
$(function(){
    $(".li").find('input').click(function(){alert('li>input');});
    $(".li").click(function(){alert('li');});
    $('input').click(function(){alert('input');});
});
</script>
</head>

<body>
<ul>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
</ul>
</body>

推荐答案

如果将两个事件处理程序绑定到完全相同的对象,则以先到先服务为准.附件中的第一个将首先执行.

If two event handlers are bound to the exact same object, it would be first come, first serve. The first one attached will execute first.

但是,您的示例看起来有些不同.看来您还有一个事件绑定到input对象,而另一个事件绑定到父li对象.在这种情况下,事件实际发生的那个(在这种情况下可能是input元素)将首先发生,然后事件冒泡至父对象,然后它们才发生.

But, your example looks a bit different. It looks like you also have one event bound to the input object and others to the parent li object. In that case, the one where the event actually originated (presumably the input element in this case) will occur first and then the event will bubble up to the parent objects and they will occur later.

如果您想停止冒犯父母,可以使用jQuery的 event.stopPropagation() ,事件将不会到达父级,也永远不会触发其事件处理程序.看起来像这样:

If you want to stop the bubbling up to the parents, you can use jQuery's event.stopPropagation() and the event will not reach the parents and never trigger their event handlers. That would look like this:

$('input').click(function(e) {
    e.stopPropagation();
    alert('input');
});

根据stopPropagation()的jQuery文档,它不会停止同一对象上的其他事件处理程序,而只会停止父对象上的事件处理程序,这些事件处理程序通常会通过冒泡父树来获取事件.

Per the jQuery documentation for stopPropagation(), it does not stop other event handlers on the same object, only event handlers on parent objects that would normally get the event via bubbling up the parent tree.

您可以在这里看到区别: http://jsfiddle.net/jfriend00/L33aq/

You can see the difference here: http://jsfiddle.net/jfriend00/L33aq/

这篇关于将多个事件处理程序绑定到一个元素时的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆