jQuery:陷阱所有点击事件之前,它们发生? [英] jQuery: Trap all click events before they happen?

查看:184
本文介绍了jQuery:陷阱所有点击事件之前,它们发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的页面上,我有很多种响应点击事件的元素。
有时候,我需要根据一些全局标志来阻止所有的点击。



现在在每个事件中,我检查该标志,例如:

  var canClick = false; //全局标志

//示例点击事件:
$(#someDiv)click(function(){
if(!canClick)return;

//有些东西...
});

我想做的是有一个元素捕获所有点击事件任何其他元素。



我试过在 这样做,但这些事件只发生在其他点击事件之后。



例如:

  $(#someDiv)click(function {){console.log click);}); 

$(document).click(function(){console.log(Document click);});

//当我点击someDiv元素时,它打印:
> someDiv点击
>文档点击

我也尝试了把一个全屏的div放在一切之上,问题是没有任何点击通过这个全屏幕div传播。此外,我不想依赖创建额外的元素来捕获点击,因为它感觉有点hacky。



我可能会覆盖jQuery点击功能,以便我可以



感谢任何帮助

解决方案

是,使用.addEventListener()并将第3个选项设置为 true



这里有一个例子,这将阻止所有的点击处理程序执行:

  document.addEventListener('click',function(e){
e.stopPropagation();
}真正);

请参阅此处:



http://jsfiddle.net/wLwMh/1/


On my page I have a lot of various elements which respond to click events. There are times when I need to block all clicks based on some global flag. Is there a way I can make this check in a centralized location?

Right now in each event I check for the flag, for example:

var canClick = false; // Global flag

// Sample click event:
$("#someDiv").click(function(){
  if(!canClick) return;

  // Some stuff ...
});

What I'd like to do is have one element which traps all click events before any other elements.

I tried doing it on document but these events only occur after the other click events.

Example:

$("#someDiv").click(function(){ console.log("someDiv click"); });

$(document).click(function(){ console.log("Document click"); });

// When I click on the someDiv element it prints:
> someDiv click
> Document click

I also tried putting a full screen div on top of everything and using this to trap events but the problem there was that none of the clicks were being propagated through this full screen div. Also I don't want to rely on creating extra elements to trap clicks as it feels a little hacky.

Could I maybe overwrite the jQuery click function so that I can put my little check in there?

Is there something obvious I'm missing here?

Thanks for any help.

解决方案

Yes, use .addEventListener() and set the 3rd option to true. This will bind the listener to the capture phase and execute the function before anything else gets executed.

Here's an example where this will stop all click handlers from executing:

document.addEventListener('click', function(e) {
    e.stopPropagation();
}, true);

See it in action here:

http://jsfiddle.net/wLwMh/1/

这篇关于jQuery:陷阱所有点击事件之前,它们发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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