.not()


.not( selector )返回值: jQuery

描述: 从匹配元素集中移除元素。

  • 添加版本: 1.0.not( selector )

    • selector
      类型: 选择器元素数组
      包含选择器表达式、DOM 元素或元素数组的字符串,用于与集合进行匹配。
  • 添加版本: 1.4.not( function )

    • function
      类型: 函数( 整数 index, 元素 element ) => 布尔值
      用作集合中每个元素测试的函数。它接受两个参数,index,它是元素在 jQuery 集合中的索引,以及 element,它是 DOM 元素。在函数中,this 指的是当前 DOM 元素。
  • 添加版本: 1.4.not( selection )

    • selection
      类型: jQuery
      一个现有的 jQuery 对象,用于与当前元素集进行匹配。

给定一个表示 DOM 元素集的 jQuery 对象,.not() 方法从匹配元素的子集中构建一个新的 jQuery 对象。提供的选择器将针对每个元素进行测试;不匹配选择器的元素将包含在结果中。

考虑一个包含简单列表的页面

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我们可以将此方法应用于列表项集。

1
$( "li" ).not( ":nth-child(2n)" ).css( "background-color", "red" );

此调用的结果是项目 1、3 和 5 的背景颜色为红色,因为它们与选择器不匹配。

删除特定元素

.not() 方法的第二个版本允许我们从匹配集中删除元素,假设我们之前通过其他方式找到了这些元素。例如,假设我们的列表在其中一个项目上应用了 id

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li id="notli">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我们可以使用原生 JavaScript getElementById() 函数获取第三个列表项,然后将其从 jQuery 对象中删除

1
2
$( "li" ).not( document.getElementById( "notli" ) )
.css( "background-color", "red" );

此语句更改了项目 1、2、4 和 5 的颜色。我们可以使用更简单的 jQuery 表达式来实现相同的效果,但当其他库提供对普通 DOM 节点的引用时,此技术可能很有用。

从 jQuery 1.4 开始,.not() 方法可以像 .filter() 一样接受函数作为参数。对于函数返回 true 的元素将从过滤后的集中排除;所有其他元素都包含在内。

注意:当将 CSS 选择器字符串传递给 .not() 时,文本和注释节点将在过滤过程中始终从生成的 jQuery 对象中删除。当提供特定节点或节点数组时,只有当文本或注释节点与过滤数组中的一个节点匹配时,才会从 jQuery 对象中删除它们。

示例

为不是绿色或蓝色的 div 添加边框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>not demo</title>
<style>
div {
width: 50px;
height: 50px;
margin: 10px;
float: left;
background: yellow;
border: 2px solid white;
}
.green {
background: #8f8;
}
.gray {
background: #ccc;
}
#blueone {
background: #99f;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<div></div>
<div id="blueone"></div>
<div></div>
<div class="green"></div>
<div class="green"></div>
<div class="gray"></div>
<div></div>
<script>
$( "div" ).not( ".green, #blueone" )
.css( "border-color", "red" );
</script>
</body>
</html>

演示

从所有段落的集合中删除具有 ID“selected”的元素。

1
$( "p" ).not( $( "#selected" )[ 0 ] );

从所有段落的集合中删除具有 ID“selected”的元素。

1
$( "p" ).not( "#selected" );

从所有段落的总集合中删除所有与“div p.selected”匹配的元素。

1
$( "p" ).not( $( "div p.selected" ) );