【问题标题】:jQuery replaceWith() documentationjQuery replaceWith() 文档
【发布时间】:2018-02-08 10:10:42
【问题描述】:

我正在阅读 jQuery 文档,发现了一个我不完全理解的 replaceWith() 示例(http://api.jquery.com/replaceWith/ 的最后一个示例)。我将在 jQuery 文档 replaceWith() 页面上发布一个指向这篇文章的链接作为评论,以帮助其他刚接触 jQuery 和 DOM 操作的人。

具体来说,我不完全理解“$container”在:

"$("p").append( $container.attr("class") );"

我期待上面的代码将单词“inner”附加到“p”内容中,因为在创建变量时调用了“replaceWith()”方法:

var $container = $("div.container").replaceWith(function() {
    return $(this).contents();
});

但是,“$("p").append($container.attr("class"));"实际上附加了“容器”这个词,而不是“内部”这个词。

似乎变量“$container”实际上引用了被替换的 div,“$("div.container")”,而不是替换内容,“$(this).contents();”。

两个问题:

  1. 在这种情况下,“replaceWith()”在做什么?
  2. 我看不到的操作顺序或“attr()”方法有什么特别之处吗?

这里是完整的代码:

<!DOCTYPE html>
<html>
<head>
    <style> 
    .container { background-color: #991; }
    .inner { color: #911; }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<p>
    <button>Replace!</button>
</p>
<div class="container">
    <div class="inner">Scooby</div>
    <div class="inner">Dooby</div>
    <div class="inner">Doo</div>
</div>

<script>
$('button').bind("click", function() {
    **var $container = $("div.container").replaceWith(function() {
        return $(this).contents();
    });**

    **$("p").append( $container.attr("class") );**
});
</script>

</body>
</html>

【问题讨论】:

    标签: jquery replacewith


    【解决方案1】:

    From the .replaceWith() documentation:

    .replaceWith() 方法与大多数 jQuery 方法一样,返回 jQuery 对象,以便其他方法可以链接到它。 但是必须注意返回的是原始的jQuery对象。此对象指的是已从 DOM 中删除的元素,而不是替换它的新元素。

    ...所以你看到的是预期的行为,$container 应该并且确实指的是 被替换的,而不是替换。

    【讨论】:

    • 谢谢尼克!作为 jQuery 的新手,我只是对“jQuery 对象”的定义感到困惑,并忽略了文本的“对象引用元素”部分。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多