.not()
.not( selector ) 返回: jQuery
描述: 刪除匹配的元素集合中元素。
-
version added: 1.0.not( selector )
selector選擇器字符串,用于確定到哪個前輩元素時停止匹配。
-
version added: 1.0.not( elements )
elements匹配的元素集合一個或多個DOM元素。
-
version added: 1.4.not( function(index) )
function(index)一個用來檢查集合中每個元素的函數(shù)。
this是當前的元素。
如果提供的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的索引)。
刪除特殊的元素
第二個版本.not()方法允許我們刪除匹配的元素集合中元素。假設我們已經(jīng)通過其他方式找到了一些元素。例如,假設我們有一個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()函數(shù)取第三個列表項目,軟后從一個jQuery對象刪除它:
$('li').not(document.getElementById('notli'))
.css('background-color', 'red');
此聲明的更改1,2,4和5項目的顏色。我們可以用一個簡單的jQuery表達式完成同樣的事情,但這種技術有時候可能很有用,例如,其他庫提供純DOM節(jié)點的引用。
在jQuery 1.4中,.not()方法可以采用一個函數(shù)作為參數(shù),這和.filter()方式是一樣。元素通過該函數(shù)返回true在排除過濾集合中的元素;所有其他元素都包括在內。
Examples:
Example: Adds a border to divs that are not green or blue.
<!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.min.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: Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )
Example: Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")
Example: Removes all elements that match "div p.selected" from the total set of all paragraphs.
$("p").not($("div p.selected"))