jQuery trigger not firing with bind() or on() for custom events

你说的曾经没有我的故事 提交于 2019-12-14 00:18:09

问题


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.

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?


回答1:


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');
}

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 :/




回答2:


Try delegation:

$(document).on('test', 'body', function() {
  alert('test');
});

$('body').trigger('test');

This works like live() used to. http://api.jquery.com/live/



来源:https://stackoverflow.com/questions/10885009/jquery-trigger-not-firing-with-bind-or-on-for-custom-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!