如何防止其他事件处理程序,从第一个处理程序,在jQuery [英] How to prevent other event handlers, from first handler, in jQuery

查看:110
本文介绍了如何防止其他事件处理程序,从第一个处理程序,在jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您将两个或多个事件处理程序附加到HTML元素,则将一个接一个地执行。但是,如果要停止后续事件处理程序,根据第一个处理程序中检查的条件,那么应该怎么做?



例如:

 < div id ='target'> 
< / div>

< p id ='result'>
< / p>

如果第一个处理程序被取消,我想取消第二个处理程序。

  $(function(){
var target = $('#target'),
result = $(' #result');
target.click(function(e){
result.append('first handler< br />');
//这里我要取消所有后续事件处理程序
});
target.click(function(e){
result.append('second handler< br />');
});
});你可以看到小提琴这里



PS:我知道 e.preventDefault()防止默认HTML元素的动作(例如,阻止由于点击链接而被发送的HTTP GET请求)和 e.preventPropagation()导致事件被传播到DOM树中的父元素。我也知道可以使用一个中间变量,在第一个处理程序中将其设置为true,并在随后的处理程序中检查它。但是我想看看这个问题是否有一个更加整齐,复杂的解决方案。

解决方案

请参阅 event.stopImmediatePropagation() - http://api.jquery.com/event.stopImmediatePropagation/



根据jQuery API文档,此方法:


保持处理程序的其余部分不被执行,并防止事件冒泡DOM树。



If you attach two or more event handlers to an HTML element, they would be executed one after the other. However, if you want to stop the subsequent event handlers, based on a condition checked in the first handler, then what you should do?

For example:

<div id='target'>
</div>

<p id='result'>
</p>

I'd like to cancel the second handler, if the first handler is cancelled.

$(function() {
    var target = $('#target'),
        result = $('#result');
    target.click(function(e) {
        result.append('first handler<br />');
        // Here I want to cancel all subsequent event handlers
    });
    target.click(function(e) {
        result.append('second handler<br />');
    });
});

You can see the fiddle here.

PS: I know that e.preventDefault() prevents the default action of the HTML element (for example, preventing an HTTP GET request being sent because of the click on a link), and e.preventPropagation() causes the event from being propagated to its parent elements in the DOM tree. I also know that it's possible to use a middle variable, set it to true in first handler, and check it in subsequent handlers. But I want to see if there is a more neat, sophisticated solution to this problem or not.

解决方案

See event.stopImmediatePropagation() - http://api.jquery.com/event.stopImmediatePropagation/

According to the jQuery API docs, this method:

Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

这篇关于如何防止其他事件处理程序,从第一个处理程序,在jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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