javascript怎样 获取表格奇数行偶数行

当鼠标移到奇数行是一种颜色,移到偶数行是另一种颜色。
怎样获取表格奇数行偶数行

1、遍历tr,得到鼠标所在tr的索引值,然后用二楼所说的方法判断奇偶;
2、用jQuery方便很多,在选择器后面加上":even"便选择的是索引值为偶数的元素,加":odd"便是索引值为奇数的元素。

下面是实现的代码,包括jQuery的:
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery/jquery-1.4.2.js"></script>
<script type="text/javascript">
function changeStyle(elementId) {
var testTable = document.getElementById("testTable").children[0];
for(var i = 0; i < testTable.children.length; i++) {
if(testTable.children[i] == elementId) {
if(i % 2 == 1) //奇数
elementId.style.background = "red";
else //偶数
elementId.style.background = "blue";
}
}
}

//清除样式
function changeBack(elementId) {
elementId.style.background = "";
}

/**
* jQuery方法:
*/
$(document).ready(function() {
$("#jqueryTable tr:even").mouseover(function() {
$(this).css("background", "red");
});
$("#jqueryTable tr:odd").mouseover(function() {
$(this).css("background", "blue");
});
$("#jqueryTable tr").mouseout(function() {
$(this).css("background", "");
});
});
</script>
</head>
<body>
<table id="testTable" border="1">
<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">
<td>第</td><td>一行</td>
</tr>
<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">
<td>第</td><td>二行</td>
</tr>
<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">
<td>第</td><td>三行</td>
</tr>
<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">
<td>第</td><td>四行</td>
</tr>
<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">
<td>第</td><td>五行</td>
</tr>
</table>

<table id="jqueryTable" border="1">
<tr>
<td>第一行</td>
</tr>
<tr>
<td>第二行</td>
</tr>
<tr>
<td>第三行</td>
</tr>
<tr>
<td>第四行</td>
</tr>
<tr>
<td>第五行</td>
</tr>
</table>
</body>
</html>
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-10
用取模函数 % 如: 10%2 = 0 9%2=1
10除2 余0
9除2 余1

这样就可以了
第2个回答  2010-04-10
鼠标放上的时候触发一个函数就是了,可以根据表格的属性设置特殊的标志 或者直接根据表格对象的行号来处理
第3个回答  2010-04-10
建议用jquery很简单的,网上很多。搜“jQuery 隔行变色”