jQuery: Can I automatically apply a plug-in to a dynamically added element?

前端 未结 4 1451
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 02:33

I\'m in the process of converting my web app to a fully AJAX architecture.

I have my master page that is initially loaded and a div container that is loaded with dynamic

相关标签:
4条回答
  • 2021-01-21 02:43

    The DOM 2 MutationEvent is what you really want, but unfortunately it isn't supported by IE. You'll need to either use live()/ delegate() binding in the plug-in, or (as I did when I had to work around this) use callbacks from your AJAX loaders indicating the scope of what has changed.

    0 讨论(0)
  • 2021-01-21 02:49

    It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.

    You can get the best of both worlds here, for example:

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

    This way it's only applying the plugin to the .entity-search-table elements you just loaded, since we specified a context to $(selector, context) to limit it.

    0 讨论(0)
  • 2021-01-21 02:51

    Yes - take a look at liveQuery. Example:

    $('.entity-search-table').livequery(function(){ 
        $(this).EntitySearch(); 
    });
    
    0 讨论(0)
  • 2021-01-21 02:53

    Use the live binding in your plugin code directly

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

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