初學 jQuery 時,最有效的方式之一就是把同一件事用原生 JavaScript 與 jQuery 各寫一遍,差異會一目了然。本文以「取得父元素、子元素、前後兄弟元素」為例做對照。
可直接執行的完整範例:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jQuery 與 JavaScript 對照學習(取得父子前後元素)</title>
<style type="text/css">
.c1 { background-color: green; padding: 20px; }
.c2 { background-color: red; padding: 20px; }
.c1 div { background-color: gray; }
</style>
<script type="text/javascript" src="style/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function fNext(obj) { // 原生寫法常被空白文字節點干擾,jQuery 就不受影響
// alert(obj.nextSibling.id);
alert(jQuery(obj).next().attr("id")); // 傳入 this,用 $(obj) 轉成 jQuery 物件
}
function fPrev(obj) {
// alert(obj.previousSibling.id);
alert(jQuery(obj).prev().attr("id"));
}
function fParent(obj) {
// alert(obj.parentNode.className);
jQuery(obj).parent().removeClass("c1").addClass("c2");
alert(jQuery(obj).parent().attr("className")); // className 當成屬性來取
}
function fChild(obj) {
// var childs = obj.childNodes;
var childs = jQuery(obj).children();
for (var i = 0; i < childs.length; i++) {
alert(childs[i].id);
}
// 也可以用 jQuery 的 each 遍歷
}
</script>
</head>
<body>
<div class="c1" onclick="fChild(this);">
<div id="first" onclick="fNext(this);">first</div>
<div id="second" onclick="fPrev(this);">second</div>
<div id="third" onclick="fParent(this);">parent</div>
</div>
</body>
</html>
obj.nextSibling.id 常常是 undefined;jQuery 的 next() 只取元素節點,省下判斷。removeClass().addClass() 一次改完樣式。children() 已幫你濾掉非元素節點。