本文翻译自:jQuery: outer html() [duplicate]
Possible Duplicate: 可能重复:
Get selected element's outer HTML 获取所选元素的外部HTML
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周围添加另一个包装器,但这不是一个好主意。
#1楼
参考:https://stackoom.com/question/O6KV/jQuery-外部html-重复
#2楼
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>";
#3楼
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/
#4楼
创建一个临时元素,然后clone()
和append()
:
$('<div>').append($('#xxx').clone()).html();
#5楼
Just use standard DOM functionality: 只需使用标准DOM功能:
$('#xxx')[0].outerHTML
outerHTML
is well supported - verify at Mozilla or caniuse . outerHTML
得到很好的支持 - 在Mozilla或caniuse验证。