not()
从匹配的元素集合中移除指定的元素。
.not(selector)
- selector类型: Selector。一个用于匹配元素的选择器字符串。
.not(elements)
- elements类型: Elements。要从匹配元素集合中移除的一个或多个DOM元素。
.not(function(index))
- function(index)类型: Function()一个函数用作测试集合中的每个元素。
this
是当前DOM元素。
.not(jQuery object)
- jQuery object类型: PlainObject。现有匹配当前元素集合的jQuery对象。
如果提供的jQuery对象代表了一组DOM元素,.not()
方法构建一个新的匹配元素的jQuery对象,用于存放筛选后的元素。所提供的选择器是对每个元素进行测试;如果元素不匹配的选择将包括在结果中。
考虑一个页面上一个简单的列表:
<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>
我们可以应用此方法来设置列表:
$('li').not(':even').css('background-color', 'red');
此调用的结果是列表项2和4背景色变成红色,因为它们不匹配选择(记得:even 和:odd使用基于0的索引)。
Removing Specific Elements(删除特殊的元素)
第二个版本.not()
方法允许我们删除匹配的元素集合中元素。假设我们已经通过其他方式找到了一些元素。例如,假设我们有一个ID列表应用到它的项目之一:
<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 对象中移除掉:
$('li').not(document.getElementById('notli')) .css('background-color', 'red');
述语句会改变第 1, 2, 4 和 5 列表项的背景色。我们可以用一个简单的jQuery表达式完成同样的事情,但这种技术有时候可能很有用,例如,我们还使用了其它返回结果是 DOM 节点的 JavaScript 库的话。
从jQuery 1.4开始,.not()
方法可以接受一个函数作为参数,这和.filter()
方式是一样。如果该函数返回true
,那么当前元素就不会包含在结果中。
注意:当一个CSS选择器字符串被传递给.not()
时,在过滤过程中,文字和注释节点将始终从得到的jQuery对象中被删除。当提供一个特定的节点或节点的数组时,只有当它匹配过滤数组中节点之一的时候,文本或注释节点将被包含在得到的jQuery对象中。
例子:
为不是绿色或蓝色的 div 添加边框。
<!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="https://www.lanmper.cn/static/js/jquery-3.5.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"的元素。
$("p").not( $("#selected")[0] )
从段落集合中移除 ID 是"selected"的元素。
$("p").not("#selected")
从段落集合中移除满足"div p.selected"的元素。
$("p").not($("div p.selected"))