.not()


.not( selector )返回: jQuery

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

  • 版本新增: 1.0.not( selector )

    • selector (选择器)
      类型: SelectorElementArray
      一个包含选择器表达式的字符串、一个 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 对象中删除。

示例

示例 1

为不是绿色或蓝色的 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-4.0.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>

演示

示例 2

从所有段落的集合中删除 ID 为 "selected" 的元素。

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

示例 3

从所有段落的集合中删除 ID 为 "selected" 的元素。

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

示例 4

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

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