jQuery:获取包含选择器的 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5587844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:25:42  来源:igfitidea点击:

jQuery: Get HTML including the selector?

jqueryhtmljquery-selectors

提问by Shpigford

Say I have this HTML:

假设我有这个 HTML:

<ul>
  <li id="example"><strong>Awesome</strong> example text</li>
</ul>

I want to be able to do something like $('#example').html()but right now doing that obviously only gets <strong>Awesome</strong> example text.

我希望能够做类似的事情,$('#example').html()但现在这样做显然只会得到<strong>Awesome</strong> example text.

So how can I get the HTML includingthe selected element?

那么如何获取包含所选元素的 HTML呢?

ie. <li id="example"><strong>Awesome</strong> example text</li>

IE。 <li id="example"><strong>Awesome</strong> example text</li>

I'm using jQuery 1.4.4.

我正在使用 jQuery 1.4.4。

回答by Jamie Wong

In this specific case:

在这种特定情况下:

var outerHTML = $("<div />").append($('#example').clone()).html();

See this pagefor more details.

有关更多详细信息,请参阅此页面

And the discussion here: http://api.jquery.com/html/(this explains that this isn't in jQuery core and why some logical solutions won't work)

和这里的讨论:http: //api.jquery.com/html/(这解释了这不在 jQuery 核心中以及为什么某些逻辑解决方案不起作用)

回答by phixr

You could try this:

你可以试试这个:

var html = $('<div>').append($('#example').clone()).html();

回答by Dominic Barnes

For browsers that support it, outerHTML can do that. There are jQuery plugins like thisand thisthat enable support via some clever jQuery.

对于支持它的浏览器,outerHTML 可以做到这一点。有像这样这样的jQuery 插件,可以通过一些聪明的 jQuery 实现支持。

回答by Andrey Popov

var outerHtml = $('#example').detach();

回答by ben

Anything wrong with simply using $('#example') ? This grabs the whole thing!

简单地使用 $('#example') 有什么问题吗?这抓住了整个事情!