我正在阅读 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();”。
两个问题:
- 在这种情况下,“replaceWith()”在做什么?
- 操作顺序或我没有看到的“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>