我试图了解jQuery load()的工作方式。
所以我在index.html和external.html(包含彩色的<body>
)中写了一个空的<div>
,并包含了Google的1.7.2 jquery.min.js。
如果我写
$(document).ready(function(){
$("body").load("external.html");
});
彩色的
<div>
正确显示。但是,如果我向脚本添加警报,$(document).ready(function(){
$("body").load("external.html");
alert("Loaded");
});
警报将显示,但div不会在那里。
是什么原因造成的?
最佳答案
您应使用load的comple回调(因为load
是异步的)以确保加载操作已完成。
$("body").load("external.html", function(){
alert("Loaded"); //<-- This ensures load operation is complete whether success of failure
});
使用您的代码,它将启动负载,然后执行警报(这将阻止ui),并且一旦将其关闭,您将看到内容正在加载。
$(document).ready(function(){
$("body").load("external.html"); //<-- Starts the async operation
alert("Loaded"); //<-- Just alerts and blocks the ui and once this is done and load operation is complete you will see the new contents getting loaded.
});
您会看到警报禁用了加载,因为
alert
会阻塞ui线程,直到将其关闭,并且没有脚本可以同时运行。因此,只有在您解除警报后,加载操作才会完成(提供了ajax调用需要多长时间才能加载内容)。