[英]Waiting for all DOM manipulations to finish with jQuery?
我對如何完成某項工作有一些困惑。 我正在使用稱為同位素的插件編寫具有砌體布局的作品集。 基本上是pinterest樣式布局。 我還將擁有一些過濾器,這些過濾器將自動從數據庫中獲取正確的內容,並將其插入到小胡子模板中。 現在的問題是,在運行同位素中繼輸出功能之前,如何等待所有dom插入完成。 因為如果我運行得太早,這些元素將無法正確定位。 我不想執行setTimeout()函數,因為我不確定數據庫請求將花費多長時間,並且我不想讓用戶等待太久。
有什么建議么?
查看jQuery Deferred.done()
這是該站點的示例:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<script>
/* 3 functions to call when the Deferred object is resolved */
function fn1() {
$("p").append(" 1 ");
}
function fn2() {
$("p").append(" 2 ");
}
function fn3(n) {
$("p").append(n + " 3 " + n);
}
/* create a deferred object */
var dfd = $.Deferred();
/* add handlers to be called when dfd is resolved */
dfd
/* .done() can take any number of functions or arrays of functions */
.done( [fn1, fn2], fn3, [fn2, fn1] )
/* we can chain done methods, too */
.done(function(n) {
$("p").append(n + " we're done.");
});
/* resolve the Deferred object when the button is clicked */
$("button").bind("click", function() {
dfd.resolve("and");
});
</script>
</body>
</html>
網站上也有一個演示。
您可以在insert函數的回調中調用relayOut方法。
$('#container').isotope( 'insert', /*items*/ ,function(){
$('#container').isotope( 'reLayout', callback );
} );
或者您可以將所有方法作為鏈條給出
$('#container').isotope( 'insert', /*items*/).isotope( 'reLayout', callback );
如果您正在使用ajax調用內容,則可以在jquery ajax的成功回調的最后一行上調用relayOut。 因此,在調用relayOut方法之前,每個DOM操作都已完成。
有關同位素插件的回調和鏈接方法,請參考http://isotope.metafizzy.co/docs/methods.html 。 對於jquery ajax,請訪問http://api.jquery.com/jQuery.ajax/
您當前是否在$(document).ready(function()內部運行該函數?也許您可以在$(window).load(function()內部嘗試該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.