jquery選擇器$('selector')返回的不是數組,而是封裝好的jquery對象。但這個對象有一個特別的地方,就是查詢到的節點被以下標爲屬性,添加到了jquery對象上,所以它看起來像數組,因爲它存在一些屬性是數字;
比如如下的代碼:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>find/eq</title>
</head>
<style>
.yellow { background:yellow; }
</style>
<body>
<div class="box">
<p id="nihaome">你<span>好</span>嗎</p>
<p>我很<span>好</span></p>
</div>
</body>
<script type="text/javascript" src="./static/js/jquery-1.12.4.min.js"></script>
<script>
$(".box").find("p").eq(1).addClass("yellow");
$("p").find("span").css('color','red');
console.log($(".box").find("p"));
console.log(document.getElementById("nihaome"));
</script>
</html>
console.log($(".box").find("p"))的輸出是:
console.log(document.getElementById("nihaome"))的輸出是:
如果需要訪問jquery選擇器返回的一組對象的某一個,可以使用.eq(index)方法,比如:
$(".box").find("p").eq(1).addClass("yellow");