jQuery:外部 html()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5744207/
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: outer html()
提问by vorobey
imagine what we have something like this:
想象一下我们有这样的事情:
<div id="xxx"><p>Hello World</p></div>
if we call .html function in this way:
如果我们这样调用 .html 函数:
$("#xxx").html();
we will get:
我们将获得:
<p>Hello World</p>
But i need to get:
但我需要得到:
<div id="xxx"><p>Hello World</p></div>
So, what i need to do? I think to add another wrapper around #xxx, but this is not a good idea.
那么,我需要做什么?我想在#xxx 周围添加另一个包装器,但这不是一个好主意。
采纳答案by David Tang
Create a temporary element, then clone()
and append()
:
创建一个临时元素,然后clone()
和append()
:
$('<div>').append($('#xxx').clone()).html();
回答by Andy
回答by ezmilhouse
No siblings solution:
没有兄弟姐妹的解决方法:
var x = $('#xxx').parent().html();
alert(x);
Universal solution:
通用解决方案:
// no cloning necessary
var x = $('#xxx').wrapAll('<div>').parent().html();
alert(x);
Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/
在这里小提琴:http: //jsfiddle.net/ezmilhouse/Mv76a/
回答by Steve Kelly
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
如果您不想添加包装器,则可以手动添加代码,因为您知道要定位的 ID:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";