選取指定類型(p)父元素下的第幾個子元素:
實例:
<!DOCTYPE html>
<html lang='zh-cn'>
<head>
<title>Insert you title</title>
<meta http-equiv='description' content='this is my page'>
<meta http-equiv='keywords' content='keyword1,keyword2,keyword3'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<script type='text/javascript' src='./js/jquery-1.12.1.min.js'></script>
<style type='text/css' >
*{margin:0;padding:0;} html{font:400 15px/1.2em 'Courier New';color:#666;}
div > *{margin:10px 0;cursor:pointer;} #demo{width:750px;margin:75px auto;} button{padding:5px 15px;border:0;outline:none;margin-top:-5px;border-radius:2px;font:400 12px/1.2em 'Courier New';}
.active{background-color:yellow;transition: .3s;} .hover{background-color:red;transition: .3s} p{text-indent:8px;} </style>
<script type='text/javascript'>
/** 概述 選擇同屬於一個父元素之下,並且標簽名相同的子元素中的第n個。 因為jQuery的實現:nth-是嚴格來自CSS規范,n值是“1-indexed”,也就是說,從1開始計數。對於所有其他選擇器表達式比如:eq()或 :even ,jQuery遵循JavaScript的“0索引”的計數。 */ $(function(){ $("span:nth-of-type(2)").addClass('hover'); }); </script>
</head>
<body>
<div id='demo'>
<div>
<span>John</span>
<b>Kim</b>
<span>Adam</span>
<b>Rafael</b>
<span>Oleg</span>
</div>
<div>
<b>Dave</b>
<span>Ann</span>
</div>
<div>
<i><span>Maurice</span></i>
<span>Richard</span>
<span>Ralph</span>
<span>Jason</span>
</div>
</div>
</body>
</html>