.not()


.not( selector )返回: jQuery

描述: 从匹配的元素集合中移除指定的元素。

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

    • selector
      类型: Selector
      一个用于匹配元素的选择器字符串。
  • 添加的版本: 1.0.not( elements )

    • elements
      类型: Elements
      要从匹配元素集合中移除的一个或多个DOM元素。
  • 添加的版本: 1.4.not( function(index) )

    • function(index)
      类型: Function()
      一个函数用作测试集合中的每个元素。this 是当前DOM元素。
  • 添加的版本: 1.4.not( jQuery object )

    • jQuery object
      类型: PlainObject
      现有匹配当前元素集合的jQuery对象。

如果提供的jQuery对象代表了一组DOM元素,.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(':even').css('background-color', 'red');

此调用的结果是列表项2和4背景色变成红色,因为它们不匹配选择(记得:even 和 :odd使用基于0的索引)。

Removing Specific Elements(删除特殊的元素)

第二个版本.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 节点的 JavaScript 库的话。

从jQuery 1.4开始,.not()方法可以接受一个函数作为参数,这和.filter()方式是一样。如果该函数返回 true,那么当前元素就不会包含在结果中。

例子:

Example: 为不是绿色或蓝色的 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
<!DOCTYPE html>
<html>
<head>
<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="http://code.jquery.com/jquery-latest.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>

Demo:

Example: 从段落集合中移除 ID 是 "selected" 的元素。

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

Example: 从段落集合中移除 ID 是 "selected" 的元素。

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

Example: 从段落集合中移除满足 "div p.selected" 的元素。

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