我试图用jQuery获取所选对象的HTML。我知道.html()函数;问题是我需要包含所选对象的HTML(在本例中为表行,其中.HTML()仅返回行内的单元格)。
我四处搜索,发现了一些非常“黑客”类型的方法来克隆对象,将其添加到新创建的div等,但这似乎真的很肮脏。有没有更好的方法,或者jQuery(1.4.2)的新版本是否提供任何类型的outerHtml功能?
我试图用jQuery获取所选对象的HTML。我知道.html()函数;问题是我需要包含所选对象的HTML(在本例中为表行,其中.HTML()仅返回行内的单元格)。
我四处搜索,发现了一些非常“黑客”类型的方法来克隆对象,将其添加到新创建的div等,但这似乎真的很肮脏。有没有更好的方法,或者jQuery(1.4.2)的新版本是否提供任何类型的outerHtml功能?
当前回答
使用普通JavaScript非常简单。。。
document.querySelector('#selector')
其他回答
为了真正实现jQuery风格,您可能希望outerHTML()是一个getter和setter,并且其行为尽可能类似于html():
$.fn.outerHTML = function (arg) {
var ret;
// If no items in the collection, return
if (!this.length)
return typeof arg == "undefined" ? this : null;
// Getter overload (no argument passed)
if (!arg) {
return this[0].outerHTML ||
(ret = this.wrap('<div>').parent().html(), this.unwrap(), ret);
}
// Setter overload
$.each(this, function (i, el) {
var fnRet,
pass = el,
inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";
if (!el.outerHTML)
el = $(el).wrap('<div>').parent()[0];
if (jQuery.isFunction(arg)) {
if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
el[inOrOut] = fnRet;
}
else
el[inOrOut] = arg;
if (!el.outerHTML)
$(el).children().unwrap();
});
return this;
}
工作演示:http://jsfiddle.net/AndyE/WLKAa/
这允许我们向outerHTML传递一个参数,该参数可以是
一个可取消的函数-函数(index,oldOuterHTML){}-,其中返回值将成为元素的新HTML(除非返回false)。字符串,该字符串将被设置为每个元素的HTML。
有关详细信息,请参阅jQuery文档For html.()。
请注意,Josh的解决方案仅适用于单个元素。
可以说,“外部”HTML只有在只有一个元素时才真正有意义,但在某些情况下,将HTML元素列表并将其转换为标记是有意义的。
扩展Josh的解决方案,此解决方案将处理多个元素:
(function($) {
$.fn.outerHTML = function() {
var $this = $(this);
if ($this.length>1)
return $.map($this, function(el){ return $(el).outerHTML(); }).join('');
return $this.clone().wrap('<div/>').parent().html();
}
})(jQuery);
编辑:Josh的解决方案解决了另一个问题,请参见上面的评论。
$("#myTable").parent().html();
也许我没有正确理解您的问题,但这将获得所选元素的父元素的html。
这就是你想要的吗?
// no cloning necessary
var x = $('#xxx').wrapAll('<div></div>').parent().html();
alert(x);
在这里摆弄:http://jsfiddle.net/ezmilhouse/Mv76a/
我相信目前(2012年5月1日),所有主流浏览器都支持outerHTML功能。在我看来,这段话就足够了。我个人会选择记住这一点:
// Gives you the DOM element without the outside wrapper you want
$('.classSelector').html()
// Gives you the outside wrapper as well only for the first element
$('.classSelector')[0].outerHTML
// Gives you the outer HTML for all the selected elements
var html = '';
$('.classSelector').each(function () {
html += this.outerHTML;
});
//Or if you need a one liner for the previous code
$('.classSelector').get().map(function(v){return v.outerHTML}).join('');
编辑:element.outerHTML的基本支持统计信息
火狐(壁虎):11。。。。发布日期:2012-03-13铬:0.2…………发布2008-09-02Internet Explorer 4.0…1997年发布歌剧7。。。。。。。。。。。。。。。。。。。。。。发布日期:2003-01-28Safari 1.3…………..2006-01-12发布