简体   繁体   中英

is it possible to re-initialize all-plugins for jQuery after ajax call?

If i received ajax response using $.post(...) , $.get(...) or something.

received response is a html format document and includes jQuery plugins.

i know jQuery plugin needs to reinitialize after ajax response. something like this

$.get('<ajaxurl>').done(function(response){
    $('#some_element').html(response);
    $('#element1_in_some_element').init_plug_in_1();
    $('#element2_in_some_element').init_plug_in_2();
    $('#element3_in_some_element').init_plug_in_3();
    $('#element4_in_some_element').init_plug_in_4();
    ....
});

But is it possible to re-initialize all plugins after ajax call?

like this

$.get('<ajaxurl>').done(function(response){
    $('#some_element1').html(response);
    $('#some_element1').init_plug_in_all();
});

!!

If you bind to the document, it should allow you to have dynamically added elements on the page which have your plugin automatically applied.

For example

$('.datePickers').datepicker();

will only fire on document load, and any NEW elements with the "datePickers" class will not have the functionality available.

But if you attach like this...

$(document).on('load','.datePickers', function() {
     $(this).datepicker();
});

It will apply to all elements with the datePickers class, even those added via AJAX

If you make a function to initialize the plugins, you can call that function when ajax call ends to reinitialize all your plugins. There aren't nothing standard to this, all depends on your plugins and your initializators. Consider something like this:

var initializePlugins = function() {
  $('selector').datepicker();
  $('selector2').fullcalendar();
  $('selector3').jScrollPane();
};

// when ajax done
$.ajax().done(function() {
  initializePlugins();
});

// when the DOM is ready        
$(document).ready(function() {
  initializePlugins();
});

If you want $('#some_element1').init_plug_in_all(); then you could write a plugin.

$.fn.init_plug_in_all = function(plug_1, plug_2, plug_3, plug_4){

  this.each(function() {

    plug_1 && $(this).init_plug_in_1();
    plug_2 && $(this).init_plug_in_2();
    plug_3 && $(this).init_plug_in_3();
    plug_4 && $(this).init_plug_in_4();

  });
};

then use like:-

$('#some_element1').init_plug_in_all(true, false, false, true);
$('.some_class').init_plug_in_all(false, false, true, true);
//etc

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