gpt4 book ai didi

javascript - 当规则不再为真时停止追加

转载 作者:行者123 更新时间:2023-11-30 15:08:15 25 4
gpt4 key购买 nike

我正在开发一个元素,我需要克隆 span.response11,将其附加到 #parent,然后将新的 div 添加到 span.response11。我已经完成了克隆过程,但是在添加新的 div 时,我的 IF 语句继续将 div 添加到已经附加了它的元素

这是我的 jquery 的 fiddle : 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 作为 child ,jquery 不应该再添加 div。

如何让我的函数停止添加更多的 div?

最佳答案

If span.response already has div.red as a child, the jQuery shouldn't add anymore div's.

你不应该使用 :has , 它用于测试相同的元素。使用 .find并检查是否有:

$("#parent > span").each(function(index, element) {
// Do the below, only when `.red` is not there inside this element.
if (!$(element).find(".red").length) {
$(element).prepend('<div class="red">This is red</div>');
}
});

另外,换句话说,我强烈反对您插入 <div>里面<span> , 作为 <span>是行内元素,而 <div>是一个街区!

关于javascript - 当规则不再为真时停止追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com