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
jQuery: Get HTML including the selector?
提问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
回答by Andrey Popov
var outerHtml = $('#example').detach();
回答by ben
Anything wrong with simply using $('#example') ? This grabs the whole thing!
简单地使用 $('#example') 有什么问题吗?这抓住了整个事情!