我正在一個項目,我需要克隆span.response11,將其追加到#parent,然後添加一個新的div到span.response11。我有克隆過程中進行,但添加新的div時,我的IF語句繼續div的添加到已經擁有它附加停止追加時,如果規則不再是真的
這裏的元素是我的jQuery小提琴: https://jsfiddle.net/4bmwbkgx/2/
// if this cloned element doesn't already have the child div.red, append it.
$("#parent > span").each(function(index, element) {
if ($(element).not(":has(.red)")) {
$(element).prepend('<div class="red">This is red</div>');
}
});
我只需要添加div.red一次。如果span.response已經有div.red作爲孩子,jquery不應該再添加div。
如何讓我的功能停止添加更多的div?
您正在克隆您已將紅色添加到的元素。重新思考你的所有邏輯 – charlietfl
@charlietfl我克隆了元素,然後追加了紅色。一旦克隆,我就會發現在點擊多次時會出現克隆哪個元素的問題。我將不得不作出調整,以便span.response內部html被克隆並用不同的東西包裝起來。 – cgrouge