2009-12-16 79 views
3

例如,如果我有HTML ul列表像如何获取使用jquery的子标记和父标记的html字符串?

<ul id="ulIdentificator"> 
    <li id="li0"></li> 
    <li id="li1"></li> 
    <li id="li2"><label id="label1"></label></li> 
</ul> 

如果我使用jQuery这样

var htmlStr = $("#li2").html(); 

其结果将是一个包含标签标记<LABEL id="label1"></LABEL></li>我需要得到一个包含HTML字符串只有字符串<LI id="li2"><LABEL id="label1"></LABEL></LI>

+1

下一个jquery问题后,你是http://stackoverflow.com/questions/1917040/can-i-get-the-full-html-represenation-of-an-htmlelment-dom-object – 2009-12-16 20:49:27

回答

6

second OuterHTML technique Andres提到(来自Web架构师的博客)适用于所有浏览器,因此它可能是更好的选择。其基本思想是,你可以通过它的另一个元素的innerHTML获取元素的外部HTML:

var outerHtml = $("<div/>").append($("#li2").clone()).html(); 

这里只有一个稍微有点棘手 - 确保clone原来的元素,这样你就不会从删除DOM。

如果你经常这样做,或者想对元素数组做这样的事情,可能值得跟随链接的例子,并做一个小插件来做到这一点。

+1

+1非常好的答案。但在[这个其他问题](http://stackoverflow.com/questions/995760/in-jquery-are-there-any-function-that-similar-to-html-or-text-but-return-the/ 5314397#5314397)你有你的同样的技术,也有一个** IFrames **问题的解决方案。 – 2011-03-15 17:42:47

0
+3

OuterHTML II技术非常简单,值得在你的答案中复制。 – 2009-12-16 19:44:42

+0

好的,这是正确的答案,但我会接受它,如果你添加一些例子不只是2个链接,其他SO人在这里看到它。 – nemke 2009-12-16 20:23:13

1

你也可以写与提出的方法一个小的jQuery插件杰夫胸骨:

// jQuery plugin 'htmlWithParent' 

jQuery(function($) { 

    $.fn.htmlWithParent = function() { return $j("<div/>").append($j(this).clone()).html(); }; 

});

,并使用这个小插件对自定义,例如:

var htmlCode = $("<p><span>Helo world!</span></p>"); 

// Return only child nodes: <span>Helo world!</span> 
var output1 = $(htmlCode).html(); 

// Return whole HTML code (childs + parent): <p><span>Helo world!</span></p> 
var output2 = $(htmlCode).htmlWithParent();

非常有用的方法。 ;)

+1

不错的工作,值得一票:) – nemke 2012-01-11 11:38:30

+0

谢谢。 ;)我总是制作小的自定义jQuery插件。代码越少,透明度越高。 – 2012-01-11 11:52:38

相关问题