jQuery 触发器不会使用 bind() 或 on() 触发自定义事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10885009/
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 not firing with bind() or on() for custom events
提问by IamFace
Can anyone tell me why this code would not be working?
谁能告诉我为什么这段代码不起作用?
$('body').on('test', function() {
alert('test');
});
$('body').trigger('test');
I'm using jquery-1.7.2.min. I do not get any errors, just nothing happens.
我正在使用jquery-1.7.2.min。我没有收到任何错误,只是没有任何反应。
I've tried putting the code inside an inline script, inside a $(document).ready()
and still nothing. I've also tried both on()
and bind()
and neither result. I see examples all over showing the same syntax, so what is different with this?
我试过将代码放在一个内联脚本中,在 a 中$(document).ready()
,但仍然没有。我也试过都on()
和bind()
和没有结果。我看到到处都是显示相同语法的示例,那么这有什么不同呢?
采纳答案by IamFace
It appears the issue lies in the DOM being ready somehow. Placing the code within inline script would not work. Placing it inside of a $(document).ready()
will work with an anonymous function, but for some reason not a function call with '( )'.. This code worked
看来问题在于 DOM 以某种方式准备好了。将代码放在内联脚本中是行不通的。将它放在 a$(document).ready()
中将与匿名函数一起使用,但由于某种原因而不是带有“( )”的函数调用。此代码有效
$(document).ready(start);
function start(){
$('body').on('test', function() {
alert('test');
});
$('body').trigger('test');
}
But this did not... *notice the function call parenthesis.
但这并没有... *注意函数调用括号。
$(document).ready(start());
function start(){
$('body').on('test', function() {
alert('test');
});
$('body').trigger('test');
}
An exact example works both ways on jsfiddle, but for some reason only one way works on my server. Which I guess bring up another question of why, but at least we can see this code does in fact work, there is some strange anomaly with my stuff :/
一个确切的例子在jsfiddle上以两种方式工作,但由于某种原因,在我的服务器上只有一种方式工作。我想这会带来另一个问题,但至少我们可以看到这段代码确实有效,我的东西有一些奇怪的异常:/
回答by Jeff
Try delegation:
尝试委托:
$(document).on('test', 'body', function() {
alert('test');
});
$('body').trigger('test');
This works like live() used to. http://api.jquery.com/live/
这就像以前的 live() 一样。 http://api.jquery.com/live/