【问题标题】:Get the outer HTML of a detached JQuery object [duplicate]获取分离的 JQuery 对象的外部 HTML [重复]
【发布时间】:2017-04-23 18:39:18
【问题描述】:

我正在通过jQuery 创建一个html 节点(示例是标签<input>,但可以是任何类型):

var x = $("<input>");

然后我通过一系列.prop()函数添加它的属性:

x.prop("id", ...).prop("class", ...);

现在某个插件不支持 JQuery 对象,而是 HTML 字符串,所以我通过这个来调用插件:

var n = plugin.method1(x.html())

我虽然会工作,但 .html() 返回一个空字符串。虽然有些人说如果我先将它附加到 DOM 树上就会解决。如何在不先将其附加到 DOM 树中的情况下获取其 HTML 字符串?

【问题讨论】:

  • 分离没关系。 html() 返回空字符串,因为它没有内容。 html() 是内部 html,而不是外部 html。

标签: javascript jquery html


【解决方案1】:

您可以使用.prop() 获取outerHTML 属性。

x.prop('outerHTML');

var x = $("<input>");
x.prop('id', 'yahooooooooo');
console.log(x.prop('outerHTML'))
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    索引它后面的 HTMLElement 并像这样访问 outerHTML 属性更简单:

    x[0].outerHTML
    

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 2013-01-13
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      相关资源
      最近更新 更多