我试图用jQuery获取所选对象的HTML。我知道.html()函数;问题是我需要包含所选对象的HTML(在本例中为表行,其中.HTML()仅返回行内的单元格)。

我四处搜索,发现了一些非常“黑客”类型的方法来克隆对象,将其添加到新创建的div等,但这似乎真的很肮脏。有没有更好的方法,或者jQuery(1.4.2)的新版本是否提供任何类型的outerHtml功能?


当前回答

这里有一个非常优化的jquery outerHTML插件:(http://jsperf.com/outerhtml-vs-jquery-clone-hack/5=>其他两个快速代码片段与FF等浏览器不兼容(11)

(function($) {

  var DIV = document.createElement("div"),
      outerHTML;

  if ('outerHTML' in DIV) {
    outerHTML = function(node) {
      return node.outerHTML;
    };
  } else {
    outerHTML = function(node) {
      var div = DIV.cloneNode();
      div.appendChild(node.cloneNode(true));
      return div.innerHTML;
    };
  }

  $.fn.outerHTML = function() {
    return this.length ? outerHTML(this[0]) : void(0);
  };

})(jQuery);

@安迪E=>我不同意你的看法。outerHMTL不需要getter和setter:jQuery已经给了我们'replaceWith'。。。

@mindsplay=>为什么要加入所有outerHTML?jquery.html只返回FIRST元素的html内容。

(抱歉,没有足够的声誉来撰写评论)

其他回答

$("#myTable").parent().html();

也许我没有正确理解您的问题,但这将获得所选元素的父元素的html。

这就是你想要的吗?

另一个类似的解决方案添加了临时DOM对象的remove()。

我同意Arpan的观点(2010年12月13日5:59)。

他的做法实际上是更好的做法,因为你不用克隆。如果您有子元素,克隆方法非常耗时,而且其他人似乎都不关心IE是否具有outerHTML属性(是的,IE实际上有一些有用的技巧)。

但我可能会创作一个有点不同的剧本:

$.fn.outerHTML = function() {
    var $t = $(this);
    if ($t[0].outerHTML !== undefined) {
        return $t[0].outerHTML;
    } else {
        var content = $t.wrap('<div/>').parent().html();
        $t.unwrap();
        return content;
    }
};

这里有一个非常优化的jquery outerHTML插件:(http://jsperf.com/outerhtml-vs-jquery-clone-hack/5=>其他两个快速代码片段与FF等浏览器不兼容(11)

(function($) {

  var DIV = document.createElement("div"),
      outerHTML;

  if ('outerHTML' in DIV) {
    outerHTML = function(node) {
      return node.outerHTML;
    };
  } else {
    outerHTML = function(node) {
      var div = DIV.cloneNode();
      div.appendChild(node.cloneNode(true));
      return div.innerHTML;
    };
  }

  $.fn.outerHTML = function() {
    return this.length ? outerHTML(this[0]) : void(0);
  };

})(jQuery);

@安迪E=>我不同意你的看法。outerHMTL不需要getter和setter:jQuery已经给了我们'replaceWith'。。。

@mindsplay=>为什么要加入所有outerHTML?jquery.html只返回FIRST元素的html内容。

(抱歉,没有足够的声誉来撰写评论)

2014年编辑:问题和此回复来自2010年。当时,还没有更好的解决方案。现在,许多其他回复都更好:比如埃里克·胡(Eric Hu)的回复,或者雷·卡查(Re Capcha)的回复。

本网站似乎为您提供了一个解决方案:jQuery:outerHTML|Yelotofu

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};