JQuery:如果元素不包含指定的词,如何按类删除元素?

时间:2021-06-30 22:41:47

标签: jquery

我正在使用 JQuery。执行此操作时:“$("div.g").remove(":contains('Opportunity')");" 当我尝试做相反的操作时:$("div.g:not").remove(":contains('Opportunity')"),它不起作用。我很想知道我哪里出错了。

1 个答案:

答案 0 :(得分:1)

您应该将 :not 应用于传递给 remove 的选择器:

$("div.g").remove(':not(:contains("Opportunity"))');

... 或使用 .not() 过滤链传递给 .remove() 的元素:

$("div.g").not(':contains("Opportunity")').remove();

下面的代码片段展示了两种方法的实际效果:

$('button.drop').click(() => {
  $("div.g").remove(':not(:contains("Opportunity"))');
}); 

$('button.drop_by_not').click(() => {
  $("div.g").not(':contains("Opportunity")').remove();
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="g">One</div>
<div class="g">Two</div>
<div class="g">Opportunity</div>
<div class="g">Opportunity Strikes</div>
<div class="g">Three Strikes</div>
<button class="drop">Drop!</button>
<button class="drop_by_not">Drop by Not!</button>

您最初编写它的方式(即使 :not 已传递 correctly,并且未附加到选择器),它已被应用于 div.g 元素,而是还原 {{1} } 规则。

相关问题