jQuery 多事件处理程序 - 如何取消? [英] jQuery Multiple Event Handlers - How to Cancel?

查看:13
本文介绍了jQuery 多事件处理程序 - 如何取消?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数在两个不同的时间绑定到一个点击事件(使用 jQuery).他们被解雇的顺序很重要.他们以正确的顺序开火.问题是,当第一个函数返回 false 时,第二个函数仍在触发!

I have two functions bound to a click event at two different times (using jQuery). The order in which they are fired is significant. They are firing in the correct order. The problem is, when the first function returns false, the second function is still firing!

如何正确取消活动?

示例代码:

$(document).click(function() { 
  alert('a');
  return false;
});

$(document).click(function() {
  alert('b');
});

单击页面时,您仍会看到b"警告消息.这是不可接受的!

You will still see the "b" alert message when clicking the page. This is unacceptable!

推荐答案

使用 stopImmediatePropagation jQuery 事件对象的函数.

Use the stopImmediatePropagation function of the jQuery event object.

阻止其余的处理程序被执行.此方法还通过调用 event.stopPropagation() 来停止冒泡.

Keeps the rest of the handlers from being executed. This method also stops the bubbling by calling event.stopPropagation().

$(document).click(function(event) { 
  alert('a');
  event.stopImmediatePropagation();
  return false;
});

$(document).click(function() {
  alert('b');
});

这篇关于jQuery 多事件处理程序 - 如何取消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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