jQuery中有許多的選擇器的方法,在這里列舉一些常用的選擇器供和打擊交流。
整體的html代碼如下:
1、通過id查找元素
$('#div2').css('color', 'blue');
2、通過class查找元素
?$('.div1').css('color', 'red');
3、通過標(biāo)簽名
$('span').css('color', 'yellow');
4、群組選擇器
$('span, p').css('background-color', 'pink');
5、后代選擇器
$('div span').css('font-size', '2em')
6、直接子選擇器
$('.container > span').css('border', '1px dashed red');
7、first選擇器與last選擇器
如果使用:fist或者:last,則沒有父級標(biāo)簽
// first
$('li:first').css('color', 'blue');? ? ?? //此時選中的是html中所有的li里的第一個li
// last
$('li:last').css('color', 'red');???????? //此時選中的是html中所有的li里的最后一個li
8、:first-child與:last-child選擇器
如果使用:first-child或者:last-child,則從子集的區(qū)域內(nèi)查找
// :first-child
$('li:first-child').css('color', 'blue'); ? ? ? //此時選中的是? 分別在2個ul中的第一個li
// :last-child
$('li:last-child').css('color', 'red');?????? //此時選中的是? 分別在2個ul中的最后一個li
9、:eq()選擇器
eq和:first類似,不區(qū)分位置,并且下標(biāo)從0開始
$('li:eq(7)').css('background-color', 'yellow');
10、:nth-child()選擇器
:nth-child和:first-child類型,區(qū)分位置,下標(biāo)從1開始
$('li:nth-child(3)').css('background-color', 'yellow');
11、:not()選擇器
用于排除某些元素,如果是多個,直接在not()后面的小括號中使用群組選擇器
$('.wrapper > *:not(p, h3)').css('background-color', 'cyan');
12:odd與:even選擇器
$('li:odd').css('background-color', 'blue');? ? ? // 代表偶數(shù)元素,根據(jù)下標(biāo),下標(biāo)為1的元素
$('li:even').css('background-color', 'blue');? ? ? // 代表奇數(shù)元素,根據(jù)下標(biāo),從0開始
$('li:nth-child(odd)').css('background-color', 'blue');? ? ? // 代表奇數(shù)元素,根據(jù)下標(biāo),從1開始
$('li:nth-child(even)').css('background-color', 'blue');? ? ? // 代表偶數(shù)元素,根據(jù)下標(biāo),從2開始
13、通過屬性選擇器獲取元素
$('p[title]').html('我是通過屬性選擇器修改后的內(nèi)容');
13、在表單中對應(yīng)的選擇器
$(':input').css('background-color', 'blue');
// $(':text').css('background-color', 'blue');? ? ? ? // 可以直接編寫input的type的值去選取元素
// $(':password').css('background-color', 'blue');
// $(':checkbox').css('background-color', 'blue');
// $(':checked').css('background-color', 'red');? ? // 選取默認(rèn)選中的元素
在jQuery中常用的選擇器大概有這些,后期再進(jìn)行跟進(jìn),在下一篇文章中主要使用jquery來進(jìn)行一些DOM的節(jié)點(diǎn)操作。