简体   繁体   中英

Reinitialize jQuery on Window Load event after AJAX

I have the following jQuery code that adjusts the product grid on the Window Load event:

$j(window).load(function(){
    // Remove list class if thumbview
    if ( $j("ul#products-list").hasClass("thumb_view") ) {
    $j("ul#products-list").removeClass("list") };
    // Equalize all thumb heights on switch if list view default
    var maxHeight = 0;
    $j('ul.thumb_view div.product-container').each(function() { maxHeight = Math.max(maxHeight, $j(this).height()); }).height(maxHeight +8);
    // Undo equalized heights for list
    $j('ul.list div.product-container').css("height","auto");
});

On the page we have a way of filtering the products based on for example price. When the price range is adjusted by the customer an AJAX call takes care of the actual filtering of products. However the jQuery script is not run again and the product grid fails to load correctly. I've done a lot of research and found to solutions that could solve this issue; use an "m-ajax-after" event, or use a jQuery delegate function.

The first option would involve this piece of code:

jQuery(document).bind('m-ajax-after', function (e, selectors, url, action) {
    // reinitialize your script
});

Which I haven't managed to get it working. Knowledge on this function is very limited.

In my opinion the second option has the most chance on actual success however I haven't been able to reproduce this into code that actually works. Many topics are to be found I just can combine this with the (window).load function. What would be the right way to do this?

It's hard to say without seeing the complete code, but here's an idea:

function formatGrid() {
 // Remove list class if thumbview
 if ( $j("ul#products-list").hasClass("thumb_view") ) {
  $j("ul#products-list").removeClass("list") };
  // Equalize all thumb heights on switch if list view default
  var maxHeight = 0;
  $j('ul.thumb_view div.product-container').each(function() { maxHeight = Math.max(maxHeight, $j(this).height()); }).height(maxHeight +8);
  // Undo equalized heights for list
  $j('ul.list div.product-container').css("height","auto");
}

$j(window).load(function(){
   formatGrid();
});

And then call this function on Ajax success:

$.ajax({
  //your current ajax code
  //and then call the formatting function
  success: function() {
      formatGrid(); 
  }
});

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