jQuery 如何獲取元素
一粗合、根據(jù)標(biāo)簽屬性或者屬性值獲取
- 根據(jù)屬性獲取元素
$("p[id]').css("color","red");
這是獲取頁(yè)面p標(biāo)簽中樞性有id的元素
- 根據(jù)屬性值獲取元素
[attribute$=value],匹配給定的屬性事宜某些值得結(jié)尾的元素批什。
[attribute!=value]畦木,匹配所有不含有指定的屬性,或者屬性不等于特定值得元素垫卤,等駕馭:not([attr=value])
[attribute*=value],匹配給定的屬性是以包含某些值得元素横堡。
@:匹配包含給定屬性的元素莺丑。
[attribute^=value]: 匹配給定的屬性是以某些值得開始的元素
- 根據(jù)標(biāo)簽選擇器以及父子節(jié)點(diǎn)獲取指定元素
- 根據(jù)下標(biāo)獲取元素
<script type="text/javascript">
$(function(){
$("p").eq(2).css("color","red");
$("p").eq(3).css("color","red");
})
</script>
- 獲取指定條件一致和指定范圍的元素
<script type="text/javascript">
$(function().css("color","red");
})
("p").slice(5,7).css("color","red");
})
</script>
* 獲取與條件表達(dá)式一致的元素
<script type="text/javascript">
jQuery(function){
$("p").each(function(){
switch(true){
case$(this).is(".center"):
$(this).css("color","red");
break;
case$(this).is(".aa"):
$(this).css("color","yellow");
break;
}
})
})
</script>
- 獲取元素的上一個(gè)元素和下一個(gè)元素
//獲取元素的下一個(gè)元素
jQuery(function(){
$("p").next(".yes").css("color"."red");
})
//獲取元素的上一個(gè)元素
jQuery(function(){
$("p").prev(".yes").css("color","red");
})
- 獲取元素的父元素和子元素
//獲取元素的父元素
jQuery(function(){
$("p").parent().css("color","red");
})
//獲取元素的子元素
jQuery(function(){
$("#aa").children(".yes").css("color","red");
})
jQuery 的鏈?zhǔn)讲僮魇窃鯓拥?/h2>
一玻靡、增
$('body')//獲取document.body
$('body').append($(<div>1</div>))//添加小兒子
$('body').append('<div>1</div>')//更方便添加
$('body').prepend(div或$div)//添加大兒子
$('#test').after(div或$div)//添個(gè)弟弟
$('#test').before(div或$div)//添個(gè)哥哥
二结榄、刪
$div.remove()
$div.empty()
三、改
$div.text(?)//讀寫文本內(nèi)容
$div.html(?)//讀寫HTML內(nèi)容
$div.attr('title',?)//讀寫屬性
$div.css({color:'red'})//讀寫style//$div.style更好
$div.addClass('blue')/removeClass/hasClass
$div.on('click',fn)
$div.off('click',fn)
//$div可能對(duì)應(yīng)了多個(gè)div元素
「資料來(lái)源:饑人谷」