使用jQuery获取.get返回的div元素的HTML

我正在尝试获取.get请求返回的特定div的HTML(.get请求,返回带有3个不同ID的3个div的HTML数据)

这是我的代码:

$.get("ajax/learn-more.html", function(data){ var $response = $(data); alert($response.find('#main-images')); // <= prints [Object object] alert("Data Loaded: " + data); // <= displaysthe whole html of learn-more.html // how can I get the html of a div in learn-more.html with id="main-images" ??? }); 

编辑:

learn-more.html的内容:

 
Foo Bar
:D

$response.find('#main-images')将返回一个空的 jQuery对象。 所选元素都没有ID main-images的后代。 相反,所选元素之一就是您要查找的元素。

要获得对div的引用,请使用.filter() [docs]

 $response.filter('#main-images'); 

如果要获取HTML,请先将内容附加到空div并删除不需要的元素:

 var container = $('
').html(data); container.children().not('#main-images').remove(); var html = container.html();

或使用outerHTML插件 :

 var html = $response.filter('#main-images').outerHTML(); 

$(data)返回一个元素数组,而不是普通的jQuery对象。 $(data)[1]包含#main-images元素。

正如Felix Kling所回答的那样,你可以使用filter而不是find

 $(data).filter('#main-images').html();