2011-06-22 38 views
3

我有以下HTML摘录:jQuery选择用于动态地生成的元素

console.log($('#contentX h1')); 

输出是

[<h1>​MyHeading1​</h1>​] 

<div id="contentX"><h1>MyHeading1</h1></div> 

我可以用jQuery选择具有以下syccessfully代码段

但是,它确实不是工作时我动态从容装载内容。例如,

HTML代码片段:

<div id="content"></div> 

jQuery代码片段:

$('#content').load('foo.html')); // the content is loaded correctly with <h1> tag 

jQuery代码片断并工作:

console.log($('#content h1')); // it returns []. I was expecting to return something. 

我想知道,如果这是类似于事件绑定的行为:.click()vs .live ()。

在此先感谢您的帮助。

+0

的,什么是'foo.html'包含哪些内容? – Dogbert

回答

8

load函数是异步的,这意味着它开始加载,然后在后台继续执行,然后继续执行脚本的其余部分。它不等待load首先完成。

您可以将函数附加到load调用,以告诉jQuery在加载完成后执行此操作。
下面是一个例子:

$('#content').load('foo.html', function() {  
    console.log($('#content h1')); 
}); 
2
$('#content').load('foo.html', function() { 
    console.log($('#content h1')); 
}); 
1

负载的jQuery的简写AJAX方法之一,而同样的动画功能等,它不会等到它完成加载外部文件(foo.html )以运行。尝试把执行console.log(或任何你想在那里)作为回调:

(...).load([url], function() { 
    console.log("whatever"); 
} 

您也可以尝试抓取网页时使用回调捕获错误:

(...).load([url], function(response, status, xhr) { 
    if (status == "error") { 
    alert("Well, that didn't really work, here's the reason why:" + xhr.statusText); 
    } 
} 

参考在jQuery的API .load页面,以进一步挖掘:http://api.jquery.com/load/

希望这对你的作品