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

JavaScript015

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>

<script type="text/javascript">

(function() {

//m偶数, n奇数

var m = 0, n = 0

var t = [1,2,3,4,5,6,7,8,9,4,4,4]

for (var j in t) {

t[j] % 2 === 0 ? m++ : n++

}

alert(m)

})()

</script>