1. 程式人生 > >jQuery遍歷not的用法

jQuery遍歷not的用法

函數 otl 其中 簡單 fun cto jquery func 給定

從包含所有段落的集合中刪除 id 為 "selected" 的段落:

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

定義和用法

not() 從匹配元素集合中刪除元素。

語法 1

.not(selector)
參數描述
selector 字符串值,包含用於匹配元素的選擇器表達式。

語法 2

.not(element)
參數描述
element 一個或多個需要從匹配集中刪除的 DOM 元素。

語法 3

.not(function(index))
參數描述
function(index) 用於檢測集合中每個元素的函數。this 是當前 DOM 元素。

詳細說明

如果給定一個表示 DOM 元素集合的 jQuery 對象,.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‘);

移除具體的元素

.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‘);

jQuery遍歷not的用法