我正在學習jquery,並且遇到了replaceAll方法。根據我的理解,replaceAll方法用另一個元素或選擇器去除一個目標選擇器。我創建了一個簡單的示例,其中包含多個h4標籤,並且每個標籤都具有不同顏色的不同類。當你點擊按鈕時,藍色班級應該取代紅色班級。它的工作原理,但我得到更多的藍色標題比我需要。下面是jsfiddle爲什麼replaceAll方法添加的元素比我實際上多?
HTML
<button>replaceAll</button>
<div id="ex1"><h2>Example 1</h2><p></p>
<h4 class="red">This is a header</h4>
<h4 class="blue">This is a header</h4>
<h4 class="green">This is a header</h4>
<h4 class="blue">This is a header</h4>
<h4 class="green">This is a header</h4>
<h4 class="red">This is a header</h4>
<h4 class="red">This is a header</h4>
<h4 class="red">This is a header</h4>
<h4 class="red">This is a header</h4>
<h4 class="blue">This is a header</h4>
<h4 class="green">This is a header</h4>
</div>
CSS
.red{color:red;}
.blue{color:blue;}
.green{color:green;}
JQuery的
$('button').click(function(){
$('.blue').replaceAll('.red');
});
你讀來DOCO(http://api.jquery.com/replaceall/)?該方法將「用每組匹配元素替換每個目標元素」。在你的情況*匹配元素的集合*包括*三個*藍色項目... – nnnnnn
請參閱我對類操作的回答,從你所說的是你想要實現的。其他答案和你自己的實現是對象操作的對象。 – JokerDan