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

Reinitialize jQuery on Window Load event after AJAX

本文关键字:事件 加载 jQuery 窗口 初始化 AJAX 之后      更新时间:2023-09-26

我有以下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");
});

在页面上,我们有一种基于价格过滤产品的方法。当客户调整价格范围时,AJAX调用负责实际的产品过滤。但是,jQuery脚本没有再次运行,产品网格无法正确加载。我做了很多研究,找到了可以解决这个问题的解决方案;使用"m-ajax-after"事件,或者使用jQuery委托函数。

第一个选项将涉及这段代码:

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

我还没能让它工作。关于这个函数的知识非常有限。

在我看来,第二个选项最有可能实际成功,但我还没有能够将其复制成实际工作的代码。许多主题都可以找到,我只是可以把它与(窗口)结合起来。加载函数。正确的做法是什么?

没有看到完整的代码很难说,但这里有一个想法:

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();
});

然后在Ajax成功时调用这个函数:

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