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

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

问题描述

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



如何正确取消事件? p>

示例代码:

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

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

当您点击页面时,您仍然会看到b警报消息。这是不能接受的!

解决方案

使用 stopImmediatePropagation jQuery事件对象的功能。


保持其他处理程序的执行。
此方法也通过调用event.stopPropagation()来阻止冒泡。




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

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


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!

How can I properly cancel the event?

Example code:

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

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

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

解决方案

Use the stopImmediatePropagation function of the jQuery event object.

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天全站免登陆