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

前端 未结 2 1402
北海茫月
北海茫月 2021-02-19 08:15

Can anyone tell me why this code would not be working?

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

$(\'body\').trigger(\'test\');
相关标签:
2条回答
  • 2021-02-19 08:44

    Try delegation:

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

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

    0 讨论(0)
  • 2021-02-19 08:58

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

    0 讨论(0)
提交回复
热议问题