简体   繁体   中英

Attach dynamic events to elements with Jquery On (using jquery plugins on dynamic elements)

I know you can attach events using

$(selector).on("click", "#myelement", function()
{ ... 
}).

but I want to do something like this:

$("body").on("tagsinput", "#myelement", function()
{ ... 
}).

I want my dynamic element "#myelement" to use tagsinput plugin when it is in the DOM

mainly I used jquery plugins when the element is already in the DOM like this:

$(function (){ $("#myelement").tagsinput(); });

Help help! :D

You could initialise tagsinput (if it exists) when the user clicks on the element, which I think will solve your problem.

$(document).on("click", "#myelement", function() {
  // don't add the functionality twice
  if ($(this).data("tagsinput-initialised")) return;

  // don't try to add functionality if plugin hasn't loaded
  if ($.isFunction($.fn.tagsInput)) {
    // "save" that we've applied the functionality
    $(this).data("tagsinput-initialised", true);
    // do it
    $(this).tagsinput();
  }
});

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