2017-08-14 8 views
0

ページ上のコンテナを置き換えるajaxフィルタを構築しています。 コンテンツがDOMに追加された後、新しく追加されたコンテンツの各ブロックをforeachし、その高さを取得し、それぞれのブロックを最大高さに設定する必要があります。 ここではトリッキーな部分があります。コンテンツが追加されると画像はロードされないので、ブロック全体の高さを正確に計算することはできません。 ここに私のコードです。コンテンツがロードされたときにjQueryが検出する

$.ajax({ 
    ... 
    success: function(html) { 
    $('#product-pagination-container').html(html); 
    adjustBoxHeights(); 

    //Sroll to products 
    /* 
     $('html,body').animate({ 
     scrollTop: $('#product-pagination-container').offset().top}, 
     'slow'); 
    */ 
    }, 
    error: function(err) { 
    console.log(err.responseText); 
    } 
}); 

function adjustBoxHeights() { 
    var maxHeight = 0; 
    $('.product-grid > div, .content-top .product-layout > div, .content-bottom .product-layout > div').each(function(){ 
    $(this).height('auto'); 
    if (maxHeight < $(this).height()) {maxHeight = $(this).height()} 
    }); 
    $('.product-grid > div, .content-top .product-layout > div, .content-bottom .product-layout > div').each(function(){ 
    $(this).height(maxHeight); 
    }); 
} 

解決策は、一定のタイムアウト後にadjustBoxHeightsを実行することですが、そのようなことはしません。

+0

TOT秒 –

+0

のタイムアウト後にそれを実行してください、あなたは持っていたことがありますPromiseオブジェクトを見ますか? – Catch44

+0

@MarcoSalernoサーバーの変更により、待機する時間やネットワークの速度の変化によって遅延が選択された時間が間違っていても、画像が利用できなくなる可能性があるため、これは決して信頼できる解決策にはなりません。 –

答えて

2

DOMに追加されるHTMLを制御している場合、イメージ要素に共通のクラス名を与え、そのクラスに属する要素のイベントコールバックをloadに設定することができます。 AJAXの "成功"コールバックでこれを行います。

次のloadイベントハンドラでは、適切な親/祖先要素のheightが得られます。 AJAXから入ってくるイメージがすべてを呼び出すと仮定

imgクラスに属し、それは基本的に、このようになります:

$.ajax({ 
 
    ... 
 
    success: function(html) { 
 
    $('#product-pagination-container').html(html); 
 
    
 
    // Now, that the DOM has been updated to inlcude the new images, we can 
 
    // find them in the DOM and set up a load event callback for each: 
 
    Array.prototype.slice.call(document.querySelectorAll("img")).forEach(function(pic){ 
 
     // As each images finishes loading, adjust the box heights: 
 
     pic.addEventListener("load", adjustBoxHeights); 
 
    }); 
 
    
 

 
    //Sroll to products 
 
    /* 
 
     $('html,body').animate({ 
 
     scrollTop: $('#product-pagination-container').offset().top}, 
 
     'slow'); 
 
    */ 
 
    }, 
 
    error: function(err) { 
 
    console.log(err.responseText); 
 
    } 
 
}); 
 

 
function adjustBoxHeights() { 
 
    var maxHeight = 0; 
 
    $('.product-grid > div, .content-top .product-layout > div, .content-bottom .product-layout > div').each(function(){ 
 
    $(this).height('auto'); 
 
    if (maxHeight < $(this).height()) {maxHeight = $(this).height()} 
 
    }); 
 
    $('.product-grid > div, .content-top .product-layout > div, .content-bottom .product-layout > div').each(function(){ 
 
    $(this).height(maxHeight); 
 
    }); 
 
}

+0

私はそれをしましたが、jQueryを使用しました。 – nikksan

関連する問題