gpt4 book ai didi

jQuery,从克隆元素中删除带有类的所有实例

转载 作者:行者123 更新时间:2023-12-01 07:05:01 25 4
gpt4 key购买 nike

尝试使用 jQuery 从带有子元素的克隆元素中删除具有特定类的所有选择器。原始标记:

<div id="el">
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
</div>

克隆版本应如下所示:

<div id="el">
<div class="remain">remain in clone</div>
<div class="remain">remain in clone</div>
<div class="remain">remain in clone</div>
</div>

jQuery 代码(不适合我的目的):

var clone = $('#el').clone();
clone = $(clone).remove('.remove');
clone = clone.html();
console.log(clone);

当我登录查看克隆中是否存在删除元素时,它会输出正确的数字:

console.log($(clone).find('.remove').length);

任何人都可以提供帮助。非常感谢! (不过可能重复)

最佳答案

您对 remove() 的使用不太正确,因为您提供的选择器用于过滤当前元素集,而不是查找 在其中。

要实现您的要求,您需要分别使用 find()remove(),如下所示:

var $clone = $('#el').clone();
$clone.find('.remove').remove();
var clone = $clone.html();
console.log(clone);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="el">
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
<div class="remove">remove from clone</div>
<div class="remain">remain in clone</div>
</div>

关于jQuery,从克隆元素中删除带有类的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48400934/

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