我(基本上)有这个代码-
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#loadDiv").load("mypage.html", function(){ alert($("#someText").text()) });
});
</script>
<div id="loadDiv"></div>
但是,由于 html 尚未渲染到 div 中,因此警报将显示“未定义”。
我见过这个问题 - How to wait for jQuery's load function to render loaded content before executing callback function - jack 的答案最适合我的情况。在我的实际页面上,我有八个这样的东西,并且有两秒的延迟,其中一些在 html 渲染之前仍然在运行。
除了增加愚蠢的时间延迟之外,有人有更好的建议吗?
最佳答案
根据the documentation ,load
方法在调用函数之前已经等待内容被放入元素中:
"If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed."
我已经对此进行了测试,当回调函数运行时,它确实找到了元素中加载的内容。
如果它在您的代码中不起作用,则说明您正在尝试执行问题中所示内容之外的其他操作。
关于javascript - 在 jQuery 加载命令之后,有没有办法强制等待,直到 html 渲染到 div 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206183/