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

JavaScript011

javascript怎样 获取表格奇数行偶数行,第1张

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 = 0i <testTable.children.lengthi++) {

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>

使用jquery的伪类选择器,例如

$("选择器 :odd").css("background","#0f0")//奇数行

$("选择器 :even").css("background","#ff0")//偶数行

若是用原生js就要判断,例如

for(var i = 0i <元素行数i++){

if(i%2 == 0){

//奇数行代码

}else{

//偶数行代码

}

}

而且用css也可以添加奇偶数行的样式,例如元素为tr的奇偶设置

tr:nth-child(odd){background:#0f0}

tr:nth-child(even){background:#ff0}

nth-of-type伪类选择器也能实现此效果。