[英]Get HTML of div element returned by .get with jQuery
I'm trying to get the HTML of a specific div returned by a .get request (the .get request, returns HTML data with 3 divs with 3 different ids) 我正在尝试获取.get请求返回的特定div的HTML(.get请求,返回带有3个不同ID的3个div的HTML数据)
Here's my code: 这是我的代码:
$.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" ???
});
EDIT: 编辑:
The content of learn-more.html: learn-more.html的内容:
<div id="something" class="hero-unit span-one-third" style="position: relative;">
Foo Bar
</div>
<div id="main-images" class="hero-unit span-one-third" style="position: relative;">
<div id="learn-more-photo" class="span-one-third">
<img class="thumbnail" src="http://placehold.it/300x180" alt="">
</div>
</div>
<div id="learn-more">
:D
</div>
$response.find('#main-images')
will return an empty jQuery object. $response.find('#main-images')
将返回一个空的 jQuery对象。 None of the selected elements has a descendant with ID main-images
. 所选元素都没有具有ID
main-images
的后代。 Instead, one of the selected elements is the one you are looking for. 相反,所选元素之一就是您要查找的元素。
To get the a reference to the div
use .filter()
[docs] instead : 要获得对
div
的引用,请使用.filter()
[docs] :
$response.filter('#main-images');
If you want to get the HTML, append the content to an empty div
first and remove the unwanted elements: 如果要获取HTML,请先将内容附加到空
div
并删除不需要的元素:
var container = $('<div />').html(data);
container.children().not('#main-images').remove();
var html = container.html();
or use a outerHTML
plugin : 或使用
outerHTML
插件 :
var html = $response.filter('#main-images').outerHTML();
$(data)
returns an array of elements and not an ordinary jQuery object. $(data)
返回一个元素数组,而不是普通的jQuery对象。 $(data)[1]
contains your #main-images
element. $(data)[1]
包含#main-images
元素。
As Felix Kling answered, you can use filter
instead of find
. 正如Felix Kling所回答的那样,你可以使用
filter
而不是find
。
$(data).filter('#main-images').html();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.