繁体   English   中英

等待所有的DOM操作完成与jQuery吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM