使用 jQuery 获取自己的 HTML 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8645895/
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
get self HTML code with jQuery
提问by Kupe3
<div>
<a href="#" class="selected">link1</a>
<a href="#">link1</a>
</div>
and using following
并使用以下
$('.selected').html()
I get
$('.selected').html()
我得到
link1
link1
as a return value.
作为返回值。
How can I get full html code of the selected DOM element, in this example to get
如何获取所选 DOM 元素的完整 html 代码,在此示例中获取
<a href="#" class="selected">link1</a>
<a href="#" class="selected">link1</a>
instead?
反而?
thanks
谢谢
回答by akai
jQuery object:
jQuery 对象:
$('.selected')
become to DOM object:
变成 DOM 对象:
$('.selected')[0]
UPDATE:
更新:
var str = $("<div />").append($('.selected').clone()).html();
console.log(str);
回答by Deleteman
I know that this works on Chrome, don't know about the rest:
我知道这适用于 Chrome,不知道其余的:
$("#yourElement")[0].outerHTML
That property is from javascript (not jQuery) and gives you what you're looking for.
该属性来自 javascript(不是 jQuery)并为您提供所需的内容。
回答by plong0
I made a solution similar to above, but with no cloning.
我做了一个类似于上面的解决方案,但没有克隆。
var test = $('#test').wrap('<div class="wrap-unwrap"></div>');
var str = test.parent().html();
test.unwrap();
console.log(str);
回答by techfoobar
Simply using the outerHTML
property may not work across all browsers. You will need to serialize it yourself for browsers without support for outerHTML
. See this post for an explanation: How do I do OuterHTML in firefox?
仅使用该outerHTML
属性可能不适用于所有浏览器。您需要自己为浏览器序列化它而不支持outerHTML
. 请参阅此帖子以获取解释:How do I do OuterHTML in firefox?
回答by Matmarbon
You could try this jQuery plugin: http://darlesson.com/jquery/outerhtml/
你可以试试这个 jQuery 插件:http: //darlesson.com/jquery/outerhtml/