JQuery: can I automatically apply the plugin to a dynamically added element?

I am in the process of converting my web application into a fully AJAX architecture.

I have my main page, which is initially loaded, and the div container loaded with dynamic content.

I have created several jQuery plugins that I apply to certain elements to extend their functionality. I usually call functions as follows each time the page loads:

$(document).ready(function () {

    // Enable fancy AJAX search
    $(".entity-search-table").EntitySearch();

});

This will find the appropriate div and call the plugin to enable the necessary functions.

In AJAX, I can’t just apply the plugin during page load, as the elements will be added and removed dynamically.

I would like to do something like this:

$(document).ready(function () {

    // Enable fancy AJAX search
    $(".entity-search-table").live("load", function () {
        $(this).EntitySearch();
    });

});

: , , <div> , , DOM?

, AJAX . , DOM.

!

+3
4

- liveQuery. :

$('.entity-search-table').livequery(function(){ 
    $(this).EntitySearch(); 
});
+4

, AJAX . , DOM.

, :

$("#something").load("url", function() {
  $(".entity-search-table", this).EntitySearch();
});

, .entity-search-table, , $(selector, context), .

+1

Use direct binding in your plugin code directly

jQuery.fn.EntitySearch = function() {
   this.live(..., function(){ your plugin code });
   return this;
}

code>

0
source

DOM 2 MutationEvent is what you really want, but unfortunately it is not supported by IE. You need to either use live()/ delegate()bind to the plug-in or (as was the case with this), use callbacks from your AJAX loaders, specifying the scope of the changes.

0
source

Source: https://habr.com/ru/post/1778657/


All Articles