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

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

jQuery: outer html()

jquery

提问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

Just use standard DOM functionality:

只需使用标准 DOM 功能:

$('#xxx')[0].outerHTML

outerHTMLis well supported - verify at Mozillaor caniuse.

outerHTML得到很好的支持 - 在Mozillacaniuse验证。

回答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>";