標籤:jquery filter
通過順序來選擇順序選擇的過濾器(filter)有
-
:first
-
第一個元素
-
:last
-
最後一個元素
-
:even
-
序號為偶數的元素
-
:odd
-
序號為奇數的元素
-
:eq(n)
-
序號等於n的元素
-
:lt(n)
-
序號小於n的元素
-
:gt(n)
-
序號大於n的元素
如果有如下的表格
| 0 |
even |
| 1 |
odd |
| 2 |
even |
| 3 |
odd |
| 4 |
even |
html代碼如下<table>
<tr><td>0</td><td>even</td></tr>
<tr><td>1</td><td>odd</td></tr>
<tr><td>2</td><td>even</td></tr>
<tr><td>3</td><td>odd</td></tr>
<tr><td>4</td><td>even</td></tr>
</table>
如果需要修改所有序號為偶數的tr的式樣,用jQuery則可以非常簡單的實現
$("tr:even").addClass('even')even是在css中定義的式樣
table tr.even { background: #CCC;}添加even式樣後,表格如下所示
| 0 |
even |
| 1 |
odd |
| 2 |
even |
| 3 |
odd |
| 4 |
even |
jQuery也提供了filter函數
$('ul li').filter(':first');
選取正在執行動畫的元素過濾器是:animated用法如下
$('div:animated'); // #1$('div:not(div:animated').animate({height:100}); // #2也可以使用動畫過濾器來判斷元素是否正在執行動畫
var myElem = $('#elem');if (myElem.is(':animated')) { // do something}
根據包含的內容來選擇元素過濾器:has(), contains()用法如下如果要選取包含特定文字的元素,可以使用containsHTML
<span>Hello Bob!</span>
JS
$(‘span:contains("Bob")); # contains參數區分大小寫,可以不需冒號
通過has來使用selector
$(‘div:has(p a)‘);
逆向選擇過濾器 notnot的參數也是一個selector
$(‘div:not(#content))
當然也可以使用複雜的selector
$(‘a:not(div.important a, a.nav)‘);
jQuery也提供了not方法
var anchors = $(‘a‘);anchors.click(function() { anchors.not(this).addClass(‘not-clicked‘);});
通過是否可見來選擇元素選取器 hidden, visible用法如下所示
if ($(‘#elem‘).is(‘:hidden‘)) { // Do something conditionally}$(‘p:visible‘).hide();
基於屬性來選擇元素過濾器
-
[attr]
-
是否具有此屬性
-
[attr=val]
-
attr屬性是否等於val
-
[attr!=val]
-
attr屬性不等於val
-
[attr^=val]
-
attr屬性以val開頭
-
[attr$=val]
-
attr屬性以val結尾
-
[attr~=val]
-
attr屬性包含val
-
[attr]
-
是否具有此屬性
用法
$(‘a[href="http://google.com"]‘);
連續使用多個屬性過濾器
$(‘*[title][href]‘)
根據元素類型來選擇過濾器
| jQuery selector syntax |
Selects what? |
| :text |
<input type="text" /> |
| :password |
<input type="password" /> |
| :radio |
<input type="radio" /> |
| :checkbox |
<input type="checkbox" /> |
| :submit |
<input type="submit" /> |
| :image |
<input type="image" /> |
| :reset |
<input type="reset" /> |
| :button |
<input type="button" /> |
| :file |
<input type="file" /> |
| :hidden |
<input type="hidden" /> |