为什么jquery在.load()之后没有看到页面中的变化?

wan*_*ist 1 jquery

我刚尝试用jQuery的.load方法改变我的页面内容.

虽然内容改变没有问题,但我发现如果我试图选择一些东西,jQuery仍然"看到"旧内容,例如:

页:

 <div id="mycontentarea">
   <div id="myfirstcontent"></div>
   <div id="mysecondcontent"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

替换内容:

<div id=mythirdcontent"></div>
<div id=myfourthcontent"></div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

// replace original content
$('#mycontentarea').load('replacement.html');
// print out the id of the first child
console.log($("#mycontentarea").children().attr("id"));
Run Code Online (Sandbox Code Playgroud)

控制台将打印出"myfirstcontent"而不是"mythirdcontent" - 为什么?

Jam*_*ice 6

因为load是异步的,console.log所以在更换发生之前执行调用.

将依赖于调用结果的任何代码移动load到成功完成时执行的回调:

$('#mycontentarea').load('replacement.html', function() {
    //Anything in here is executed once the content has been returned successfully
    console.log($("#mycontentarea").children().attr("id"));
});
Run Code Online (Sandbox Code Playgroud)

来自以下文档load:

如果提供"完整"回调,则在后处理和执行HTML插入之后执行.对jQuery集合中的每个元素触发一次回调,并依次设置为每个DOM元素.