获取div元素的HTML返回。获得与jQuery [英] Get HTML of div element returned by .get with jQuery
问题描述
我试图让一个不用彷徨请求返回一个特定的div的HTML(在不用彷徨请求,返回HTML数据有3个div的有3个不同的ID)
下面是我的code:
$。获得(AJAX /学习-more.html功能(数据){
变量$响应= $(数据);
警报($ response.find('#主图像')); //< =打印[Object对象]
警报(数据加载:+数据); //<的学习,more.html = displaysthe整个HTML
//我怎样才能得到一个div的学习,more.html id为主映像的HTML ???
});
编辑:
的学习,more.html内容:
< DIV ID =东西级=英雄单位跨度三分之一的风格=的位置是:相对;>
富律师
< / DIV>
< DIV ID =主图像级=英雄单位跨度三分之一的风格=的位置是:相对;>
< DIV ID =了解,更照片级=跨度三分之一>
< IMG类=缩略图SRC =http://placehold.it/300x180ALT =>
< / DIV>
< / DIV>
< DIV ID =学习 - 更多>
:D
< / DIV>
$ response.find('#主图像')
将返回空 jQuery对象。没有选择的元素与ID 主图像的后裔
。相反,选择的元素之一您正在寻找的人。
要获得一个引用 DIV
使用 .filter()
的 [文档] 的来代替:
$ response.filter('#主图像');
如果你想要得到的HTML,将内容附加到一个空 DIV
第一和删除不需要的元素:
VAR容器= $('< DIV />').html(data);
container.children()不是('#主图像)删除()。
变种的HTML = container.html();
或使用<一个href="http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html"><$c$c>outerHTML$c$c>插件:
VAR HTML = $ response.filter('#主图像)outerHTML()。
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)
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:
<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. None of the selected elements has a descendant with 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 :
$response.filter('#main-images');
If you want to get the HTML, append the content to an empty div
first and remove the unwanted elements:
var container = $('<div />').html(data);
container.children().not('#main-images').remove();
var html = container.html();
or use a outerHTML
plugin:
var html = $response.filter('#main-images').outerHTML();
这篇关于获取div元素的HTML返回。获得与jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!