jQuery触发器不使用bind()或on()触发自定义事件 [英] jQuery trigger not firing with bind() or on() for custom events
问题描述
有人可以告诉我为什么此代码无法正常工作吗?
Can anyone tell me why this code would not be working?
$('body').on('test', function() {
alert('test');
});
$('body').trigger('test');
我正在使用 jquery-1.7.2.min .我没有任何错误,什么也没发生.
I'm using jquery-1.7.2.min. I do not get any errors, just nothing happens.
我尝试将代码放入内联脚本,$(document).ready()
内,但仍然一无所获.我也尝试了on()
和bind()
,但都没有结果.我看到所有示例都显示相同的语法,那么这有什么不同?
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?
推荐答案
看来问题出在DOM准备就绪.将代码放在内联脚本中将不起作用.将其放在$(document).ready()
内部将可以使用匿名函数,但由于某种原因,不能使用'()'进行函数调用.此代码有效
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
$(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');
}
一个确切的示例在 jsfiddle 上可以同时使用,但是由于某种原因,在我的服务器上只能使用一种方法.我猜想为什么会引起另一个问题,但是至少我们可以看到这段代码确实起作用了,但是我的东西有些奇怪:/
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 :/
这篇关于jQuery触发器不使用bind()或on()触发自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!