.not()
.not( selector ) 返回: jQuery
描述: 刪除匹配的元素集合中元素。
-
version added: 1.0.not( selector )
selector選擇器字符串,用于確定到哪個(gè)前輩元素時(shí)停止匹配。
-
version added: 1.0.not( elements )
elements匹配的元素集合一個(gè)或多個(gè)DOM元素。
-
version added: 1.4.not( function(index) )
function(index)一個(gè)用來(lái)檢查集合中每個(gè)元素的函數(shù)。
this是當(dāng)前的元素。
如果提供的jQuery代表了一組DOM元素,.not()方法構(gòu)建一個(gè)新的匹配元素的jQuery對(duì)象的一個(gè)子集。所提供的選擇器是對(duì)每個(gè)元素進(jìn)行測(cè)試;如果元素不匹配的選擇將包括在結(jié)果中。
考慮一個(gè)頁(yè)面上一個(gè)簡(jiǎn)單的列表:
<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>
我們可以應(yīng)用此方法來(lái)設(shè)置列表:
$('li').not(':even').css('background-color', 'red');
此調(diào)用的結(jié)果是項(xiàng)目2和4下為紅色的背景,因?yàn)樗鼈儾黄ヅ溥x擇(記得:even 和 :odd使用基于0的索引)。
刪除特殊的元素
第二個(gè)版本.not()方法允許我們刪除匹配的元素集合中元素。假設(shè)我們已經(jīng)通過(guò)其他方式找到了一些元素。例如,假設(shè)我們有一個(gè)ID列表應(yīng)用到它的項(xiàng)目之一:
<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ù)取第三個(gè)列表項(xiàng)目,軟后從一個(gè)jQuery對(duì)象刪除它:
$('li').not(document.getElementById('notli'))
.css('background-color', 'red');
此聲明的更改1,2,4和5項(xiàng)目的顏色。我們可以用一個(gè)簡(jiǎn)單的jQuery表達(dá)式完成同樣的事情,但這種技術(shù)有時(shí)候可能很有用,例如,其他庫(kù)提供純DOM節(jié)點(diǎn)的引用。
在jQuery 1.4中,.not()方法可以采用一個(gè)函數(shù)作為參數(shù),這和.filter()方式是一樣。元素通過(guò)該函數(shù)返回true在排除過(guò)濾集合中的元素;所有其他元素都包括在內(nèi)。
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"))