检查jQuery对象中返回的DOM元素 [英] Examining the DOM elements returned in a jQuery object
问题描述
我有:
<p>Paragraph One</p>
<p>Paragraph Two</p>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<script>
var x = $('p');
x.each(function(index) {
$('body').append($(this).html().replace('<','<') + '<br>');
});
</script>
我希望看到:
<p>Paragraph One</p><br>
<p>Paragraph Two</p><br>
但是,相反,p标签本身丢失了.
But instead, the p tag itself is missing.
我试图使输出看起来像console.log,它将x标识为两(2)个段落元素.
I'm trying to make my output look like console.log, which would identity x as two (2) paragraph elements.
它将在段落中获取html,但是console.log将其显示为段落.所以我想我需要先上升然后再下降吗?
It's getting the html within the paragraph, but console.log shows it AS a paragraph. So I guess I need to go up a level and then back down again?
推荐答案
这是因为$(this).html()
仅会提供<p>
元素的内容,而不是元素本身.
This is because $(this).html()
will only give you the content of the <p>
element, not element itself.
执行此操作:
var x = $('p');
x.each(function(index) {
var p_html = this.outerHTML || $('<div>').append($(this).clone()).html();
$('body').append(p_html.replace('<','<') + '<br>');
});
这将获取每个<p>
元素,并获取其.outerHTML
属性(与innerHTML
类似,但还包括所有者的标记).
This takes each <p>
element, and gets its .outerHTML
property (which is like innerHTML
but includes the owner's tag as well).
如果不支持.outerHTML
属性(我在看Firefox!),则它会使用
If the .outerHTML
property isn't supported (I'm looking at you Firefox!) then it uses the clone()
[docs] method to make a clone of the <p>
, adds it to a new <div>
and gets the .html()
of the <div>
.
这篇关于检查jQuery对象中返回的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!