简体   繁体   English

在AJAX之后在窗口加载事件上重新初始化jQuery

[英]Reinitialize jQuery on Window Load event after AJAX

I have the following jQuery code that adjusts the product grid on the Window Load event: 我有以下jQuery代码,可在Window Load事件上调整产品网格:

$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. 当客户调整价格范围时,AJAX呼叫将负责实际的产品过滤。 However the jQuery script is not run again and the product grid fails to load correctly. 但是,jQuery脚本不会再次运行,并且产品网格无法正确加载。 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. 使用“ m-ajax-after”事件,或使用jQuery委托函数。

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. 我可以将其与(window).load函数结合起来找到许多主题。 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成功时调用此函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM