Cannot programmatically trigger jQuery click event

后端 未结 9 2199
心在旅途
心在旅途 2020-12-20 16:39

If I understand correctly, to programmatically trigger a jQuery click event attached to an object with a css class of my-button, you should be able to just do t

相关标签:
9条回答
  • 2020-12-20 17:07

    If it does not recall the events, especially the custom, which are properly recorded, it is likely that the jQuery library is loaded again, after you assign an event handler.

    Check your code using:

    jQuery (document).ready (function () {
        // Test your code here
    });
    
    0 讨论(0)
  • 2020-12-20 17:13

    You should use:

    $('.my-button').trigger("click");
    
    0 讨论(0)
  • 2020-12-20 17:13

    I had the same problem and changing the way I bound the event to the function fixed it

      var f=function() { .... }
      $('input.radioDomande').click(f);
      ...
      $(s+data.domanda[i].valore).trigger("click");
      //WRONG: It won't trigger the event
    

    then changed the binding according to the example in http://api.jquery.com/trigger/

      var f=function() { .... }
      $('input.radioDomande').bind('click', f);
      ...
      $(s+data.domanda[i].valore).trigger("click");
      //IT DOES TRIGGER THE EVENT
    
    0 讨论(0)
  • 2020-12-20 17:13

    My best guess is the handler is bound after you are trying to trigger the event.

    Try:

    var myButtons = $('<a class="my-button"/>)
                        .click(function() { /* code here */ })
                        .appendTo(parent);
    
    myButtons.click();
    

    or using your original code - trigger the event in the callback of your JSONP request.

    0 讨论(0)
  • 2020-12-20 17:14

    Odd. Have you tried .trigger('click')? Theoretically, they should be the same (looking into jQuery code right now to find out). Edit: It appears .click() is simply a proxy for .trigger('click'), so it probably won't help.

    For debugging, try to bind a live click event on the page that the widget is loaded in to.

    0 讨论(0)
  • 2020-12-20 17:19

    I don't know if cross-domain JSONP has something to do with it, however I must say that programmatically triggering a click event on a selector that has to do with an html link (<a href='...'>...</a>) doesn't work.

    I suspect it has to be some sort of browser policy, so as to block pop ups. Consider the fact that browsers, have a mechanism to track and block pop ups and mostly allow the user authorize a click action before the new link appears.

    If you could programmatically click a link via jQuery, redirection, popups and all that stuff would be easier to do, hence it's not possible. Just to be clear:

    <a class='test' href='http://www.example.com'>Link1<a/> you cannot trigger that.

    <a class='test2'>Link2</a> you can trigger an onclick here, because it doesn't contain href.

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