匹配所有行数为偶数 js

JavaScript010

匹配所有行数为偶数 js,第1张

css3支持偶数行匹配,如li:nth-of-type(even) 如果是odd表示奇数行。

对于js来说是没有直接的功能作这个匹配的,某些框架可能支持,但是也都是模拟的。实际上js总是先选中所有符合条件的元素,如tbody中的所有tr,然后把偶数行挑出来。例如document.getElementsByTagName('tr')会得到一个数组,自然0,2,4是奇数行,其它是偶数行。

jQuery框架的例子:$('div:even')其中:even表示匹配偶数行,相关的方法还有 $('div').index(),指选中的元素在其平级元素中的索引,从0开始。

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>