javascript jquery 触发自定义全局事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23782786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery trigger custom global event
提问by Enermis
I would like to do something like this
我想做这样的事情
$("#A").on("click", function(){
$.event.trigger({type:"custom"});
});
$("#B").on("custom", function(e){
$("#B").removeClass("hidden");
});
$("#C").on("custom", function(e){
alert("something");
}
Where I trigger a custom event using JavaScript. I would then like to be able to use the .on
function on different elements throughout the page. Clicking the "#A" would then trigger the event for all registered elements.
我使用 JavaScript 触发自定义事件的地方。然后我希望能够.on
在整个页面的不同元素上使用该功能。单击“#A”将触发所有已注册元素的事件。
I noticed that the trigger function is called on an element instead of globally, which is not what I want.
我注意到触发器函数是在元素上调用的,而不是全局调用的,这不是我想要的。
回答by David Domingo
I'm not sure I understand your question, but if you change your code to this:
我不确定我是否理解您的问题,但是如果您将代码更改为:
$("#A").on("click", function(){
$(document).trigger("custom");
});
$(document).on("custom", function(e){
$("#B").removeClass("hidden");
});
$(document).on("custom", function(e){
alert("something");
});
It should work. Here's a demo
它应该工作。这是一个演示