這篇把常用的 jQuery 選擇器與物件訪問方法做個系統性整理,方便日常查閱。
1、each(callback):以每個匹配元素作為上下文執行函式;return false 停止循環,return true 跳至下一輪。
$("img").each(function(){
$(this).toggle("example");
})
2、size() 與 length 相同,都回傳 jQuery 物件中元素的數量。
$("img").size(); 或 $("img").length;
3、get():取得所有匹配的 DOM 元素集合(注意回傳的是 DOM 物件,而非 jQuery 物件)。
$("img").get().reverse();
4、get(index):取得其中一個匹配元素,index 表示第幾個,可用來操作實際的 DOM 元素。
$("img").get(0); // 得到第一個匹配的 img 元素
$(this).get(0) 與 $(this)[0] 等價。
5、index(subject):搜尋與參數物件匹配的元素,並回傳其索引值。
selector1, selector2, selectorN:把匹配到的元素合併後一起回傳。
$("div,span,p.myClass");
這裡要留意幾種相似語法的差異:
1、$("span", this) —— 例如:
$("div.foo").click(function() {
$("span", this).addClass("bar");
});
2、$("div#hi")、$("p.intro") —— 例如:
$("div#hi").css("color","red");
3、$("form input") —— 例如:
$("form input").css("border", "5px solid red");
1、ancestor descendant:在指定祖先下匹配所有後代。$("div input") 選取 div 下所有 input。
2、parent > child:在指定父元素下匹配所有子元素。$("div > input")。
3、prev + next:匹配緊接在 prev 之後的 next。$("div + span")。
4、prev ~ siblings:匹配 prev 之後的所有同輩。$("form ~ input")。
1、:first 匹配第一個元素,$("tr:first") 選第一列。
2、:last 匹配最後一個元素,$("tr:last")。
3、:not(selector) 去除符合選擇器的元素;jQuery 1.3 起支援複雜選擇器(如 :not(div a)、:not(div,a))。$("input:not(:checked)")。
4、:even 匹配索引為偶數的元素(從 0 起算),$("tr:even")。
5、:odd 匹配索引為奇數的元素,$("tr:odd")。
6、:eq(index) 匹配指定索引的元素,$("tr:eq(1)") 選第二列。
7、:gt(index) 匹配索引大於給定值的元素,$("tr:gt(0)")。
8、:lt(index) 匹配索引小於給定值的元素,$("tr:lt(2)")。
9、:header 匹配 h1、h2、h3 之類標題元素,$(":header").css("background","red")。
10、:animated 匹配正在執行動畫的元素。
1、:contains(text) 匹配含指定文字的元素,$("div:contains('aaa')")。
2、:empty 匹配不含子元素或文字的空元素,$("td:empty")。
3、:has(selector) 匹配含有指定後代的元素,$("div:has(p)").addClass("test")。
4、:parent 匹配含有子元素或文字的元素,$("td:parent")。
1、:hidden 匹配所有不可見元素(type 為 hidden 的 input 也算),$("tr:hidden")。
2、:visible 匹配所有可見元素,$("tr:visible")。
1、[attribute] 匹配含指定屬性的元素,$("div[id]")。
2、[attribute=value] 匹配屬性為特定值的元素,$("input[name='username']")。
3、[attribute!=value] 匹配不含該屬性或值不等於特定值的元素,等同 :not([attr=value]),$("input[name!='username']")。
4、[attribute^=value] 匹配屬性以某些值開頭的元素,$("input[name^='user']")。
5、[attribute$=value] 匹配屬性以某些值結尾的元素,$("input[name$='letter']")。
6、[attribute*=value] 匹配屬性包含某些值的元素,$("input[name*='man']")。
7、[selector1][selector2][selectorN] 複合屬性選擇器,需同時滿足多個條件,$("input[id][name='man']")。
1、:nth-child(index/even/odd/equation) 匹配父元素下的第 N 個子或奇偶元素,$("ul li:nth-child(2)")。
2、:first-child 匹配第一個子元素,$("ul li:first-child")。
3、:last-child 匹配最後一個子元素,$("ul li:last-child")。
4、:only-child 匹配父元素中唯一的子元素,$("ul li:only-child")。
1、:input、:text、:password、:radio、:checkbox、:submit、:image、:reset、:button、:file。
2、:hidden 匹配所有不可見元素或 type 為 hidden 的元素。
1、:enabled 匹配所有可用元素,$("input:enabled")。
2、:disabled 匹配所有不可用元素,$("input:disabled")。
3、:checked 匹配所有被選中的元素(核取方塊、單選鈕,不含 select 的 option),$("input:checked")。
4、:selected 匹配所有被選中的 option 元素,$("select option:selected")。