简体   繁体   中英

Custom event in jquery

I am binding custom event on buttons to apply Jquery ui button plugin like :

      $(document).ready(function() { 
        $(".uibutton").live("CustomEvent", function() { $(this).button(); });
        $(".uibutton").trigger("CustomEvent");
      });

      <input type="button" class="uibutton" >

Now this works good for the button which are present in the MarkUP but the buttons which are created dynamically with class uibutton , this is not working. Can anybody please tell me why ?

As mentioned in the comments, the problem seems to be that even though the custom event is successfully bound even for dynamically created buttons with class uibutton, the event will still need to be triggered again every time a new button has been created. The .trigger() in your .ready() function will only affect the buttons existing at that point in time.

$(".uibutton).trigger("CustomEvent");

There is missing closure quotation.

it should be like this:

$(".uibutton").trigger("CustomEvent");

try it.

I know that you have mentioned using on() and it didn't turn out to be working, but please make sure you have used it like this:

$(document).on("click", ".uibutton", function() {
  /// My code....
});

And test it again.

The thing is, you need to add this handler to document element, which might not be obvious from documentation. Only that way you will be able to use on() just like live() . And please do use on() version, since latter will be removed from jQuery at one point or another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM