【问题标题】:jQuery to return the wrapper of the content instead of only the content [duplicate]jQuery返回内容的包装器,而不仅仅是内容[重复]
【发布时间】:2014-07-25 05:43:23
【问题描述】:

假设我有以下 HTML

<articles>

    <article id="a1">
        <!-- Content of article with id="a1" -->
    </article>

    <article id="a2">
        <!-- Content of article with id="a2" -->
    </article>

    <article id="a3">
        <!-- Content of article with id="a3" -->
    </article>

</articles>

使用 jQuery,我做了以下操作

var x = $("#a2").html();

现在,变量x 将继续:

<!-- Content of article with id="a2" -->

但是,我希望 x 包含:

<article id="a2">
    <!-- Content of article with id="a2" -->
</article>

我试过了:

var x = $("#a2").parent().html();

但这返回了所有三篇文章,这不是我想要的。我只想要文章 a2。我该怎么做?

谢谢。

【问题讨论】:

    标签: jquery jquery-selectors element return-value


    【解决方案1】:

    尝试使用.outerHTML 属性,

    var x = $("#a2")[0].outerHTML;
    

    【讨论】:

    • 为什么我必须使用索引[0]?
    • @Greeso 因为.outerHTML是一个属性,属于纯javascript的元素对象。我们必须通过从索引 0 读取元素来获取它。
    • outerHtml 不是 jquery 的属性,它是 javascript。 var x = documentElementById('a2').outerHTML;
    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2020-04-26
    • 2016-12-11
    • 2016-06-02
    • 2014-07-01
    相关资源
    最近更新 更多