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

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

问题描述

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

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?

例如:

<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 />');
    });
});

您可以在这里看到小提琴.

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

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.

推荐答案

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

根据 jQuery API 文档,此方法:

According to the jQuery API docs, this method:

阻止其余的处理程序被执行,并防止事件在 DOM 树中冒泡.

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

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

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