[英]jQuery detect when content is loaded
我正在構建一個ajax過濾器,它將替換頁面上的一個容器。 將內容添加到DOM之后,我需要為每個新添加的內容塊獲取每個塊並獲取其高度,然后將每個塊設置為最大高度。 這是棘手的部分。添加內容后,圖像不會加載,因此我無法准確計算整個塊的高度。 這是我的代碼。
$.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,但我不喜歡它。
如果您控制添加到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); }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.