标签:
一般来说我在需要写一个遍历的时候就先写一个html测试页面,用相同的结构来测试代码。如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery遍历测试</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".elan").css("font-weight", "bold");
$(".elan").bind("click", this, function() {
$(this).css("font-weight", "normal");
$(this).parent().parent().parent().parent().prev().css("font-weight", "normal");
});
$(".elan-top").css("font-weight", "bold");
$(".elan-top").bind("click", this, function() {
$(this).css("color", "green");
$(this).parent().children("td").children("table").children("tbody").children("tr").children(".elan").css("color", "green");
});
});
function tdonclick(obj) {
$(obj).parent().parent().parent().parent().prev().css("background-color", "red");
}
</script>
</head>
<body>
<table>
<tr>
<td class="elan-top">父表(1,1)</td>
<td><table>
<tr>
<td onClick="tdonclick(this);">子表(1,1)</td>
</tr>
<tr>
<td class="elan">子表(1,2)</td>
</tr>
</table></td>
</tr>
<tr>
<td class="elan-top">父表(2,1)</td>
<td><table>
<tr>
<td onClick="tdonclick(this);">子表(2,1)</td>
</tr>
<tr>
<td class="elan">子表(2,2)</td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
上面的代码要实现的效果就是点击每个“子表(*,2)”元素时,自己和同行的“父表(*,1)”粗体字变为普通字体;点击“父表(*,1)”则自己和同行的class=“elan”的子表元素变为绿色;点击“子表(*,1)”元素时,“父表(*,1)”元素背景色变为红色。
猛的一看初学者肯定会觉得上面所有代码里面都多了一层遍历,其实jQuery的遍历是根据页面DOM进行的,这也是我们经常会出错的地方,比如这里,表格其实还有一个<tbody></tobody>的元素节点,所以每次遍历到<tr></tr>的时候我们都要将这个加进去。
*这里推荐大家一种方便的查找遍历节点的方法,IE8+,Chrome浏览器都提供了开发者工具,我们可以先将网页结构编写好,然后在这里面进行调试,打开开发者工具(F12),那里面会将页面的DOM元素一一列出,只要细心查找,一般都能解决遍历的问题。如下图所示,是IE8中的开发者工具显示的页面结构,这里可以很容看到遍历的节点。

标签:
原文地址:http://www.cnblogs.com/shouce/p/5260477.html