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

时间:2015-09-15 19:54:01

标签: javascript jquery ajax

我有以下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" event,或使用jQuery委托函数。

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

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

我还没有设法让它发挥作用。关于这个功能的知识非常有限。

在我看来,第二个选项最有可能获得实际成功,但是我还没有能够将其重现为真正有效的代码。我可以找到很多主题,我可以将它与(window).load函数结合起来。什么是正确的方法呢?

1 个答案:

答案 0 :(得分:0)

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

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(); 
  }
});
相关问题