我正在通過jQuery文檔工作,發現一塊我沒有完全理解的replaceWith()示例(來自http://api.jquery.com/replaceWith/的最後一個示例)。我將發佈一個鏈接到這篇文章,作爲對jQuery文檔replaceWith()頁面的評論,以幫助其他人使用jQuery和DOM操作。jQuery replaceWith()文檔
具體來說,我不完全理解「$容器」的行爲:
"$("p").append($container.attr("class"));"
我期待上面的代碼字「內部」附加到「P」的內容,因爲「replaceWith ()」的變量創建時方法被調用:
var $container = $("div.container").replaceWith(function() {
return $(this).contents();
});
然而, 「$(」 p 「)附加($ container.attr(」 類 「));」實際上追加單詞「容器」,而不是單詞「內部」。
似乎變量「$容器」實際上引用被替換的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>
謝謝尼克!作爲jQuery的新手,我簡單地對'jQuery對象'的定義感到困惑,並且忽略了文本中的「對象引用元素」部分。非常感激。 –