且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取使用jquery的子标记和父标记的html字符串?

更新时间:2022-05-11 05:27:11

第二个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.