[JQuery]學習——高級選擇器

第一,後代選擇器

$('#box p').css('color','red');

$('#box').find('p').css('color','red');


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基礎核心</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<div id="box">
<p>pq</p>
<p>pq</p>
<p>pq</p>
<div>
<p>pq</p>
<p>pq</p>
<p>p</p>
</div>
</div>
</body>
</html>

p全部紅色


第二,子代選擇器

$('#box > p').css('color','blue');
$('#box').children('p').css('color','blue');

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基礎核心</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>

<body>
<div id="box">
<p>pq</p>
<p>pq</p>
<p>pq</p>
<div>
<p>pq</p>
<p>pq</p>
<p>p</p>
</div>
</div>
</body>
</html>

第三,next選擇器,必須緊挨着

$('#box').next().css('color','blue');


第四,nextAll選擇器

$('#box ~ p').css('color', 'red'); //兼容IE6
jQuery 爲nextAll 選擇器提供了一個等價的方法nextAll():
$('#box').nextAll('p').css('color', 'red'); //和nextAll 選擇器等價


第五,prev,prevAll選擇器

爲了補充高級選擇器的這三種模式,jQuery 還提供了更加豐富的方法來選擇元素:
$('#box').prev('p').css('color', 'red'); //同級上一個元素
$('#box').prevAll('p').css('color', 'red'); //同級所有上面的元素


第六,上下同級所有

$('#box').siblings('p').css('color', 'red'); //同級上下所有元素選定

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章