如何获取使用jquery的子标记和父标记的html字符串? [英] How to get html string of a child tag and parent tag using jquery?

查看:89
本文介绍了如何获取使用jquery的子标记和父标记的html字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有HTML ul 列表,如

For example if I have HTML ul list like

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

如果我这样使用jQuery

If I use jQuery like this

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

结果将只是包含标签标签< LABEL id = label1>< / LABEL>< / li> 我需要获取包含此< LI id =li2>< LABEL的Html字符串id =label1>< / LABEL>< / LI>

The result will be only string that contains label tag <LABEL id="label1"></LABEL></li> I need to get Html string that contains this <LI id="li2"><LABEL id="label1"></LABEL></LI>

推荐答案

第二个OuterHTML技术 Andres提到(来自Web Architects的博客)适用于所有浏览器,所以它可能是一个更好的选择。基本思想是,你可以通过使元素的外部HTML成为另一个元素的innerHTML来获得元素的外部HTML:

The second OuterHTML technique Andres mentions (from the Web Architects' Blog) works on all browsers, so it's probably a better choice. The basic idea is that you can get an element's outer HTML by making it another element's innerHTML:

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

只有一点棘手的问题 - 确保 clone 您的原始元素,所以您不会将其从DOM中移除。

There's only one slightly tricky bit - make sure to clone your original element, so you don't remove it from the DOM.

如果您经常这样做或想要对元素数组执行此操作,值得跟随链接的例子,并做一个小插件来做到这一点。

If you do this often or want to do this to arrays of elements, it's probably worth following the linked example and make a little plugin to do this.

这篇关于如何获取使用jquery的子标记和父标记的html字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆