jquery 怎么获取tr下的第二个td元素?

html-css017

jquery 怎么获取tr下的第二个td元素?,第1张

有两种方法可以获取tr下的第二个td元素:

1、使用css选择器,$("tr td:nth-child(2)")。

2、使用遍历函数eq()。

下面就以上两个方法进行实例演示:单击按钮改变所有行的第二个单元格的样式,单击任意行改变该行第二个单元格的样式。

1、HTML结构

<table id = "test">

<tr><td>1</td><td>1</td><td>2</td><td>3</td></tr>

<tr><td>2</td><td>4</td><td>5</td><td>6</td></tr>

<tr><td>3</td><td>7</td><td>8</td><td>9</td></tr>

<tr><td>4</td><td>1</td><td>2</td><td>3</td></tr>

</table>

<input type="button" id="btn" value="设置">

2、jquery代码

$(function(){

$("#btn").click(function() {

$("#test tr td:nth-child(2)").addClass('red')

})

$("#test tr").click(function() {

$(this).children('td').eq(1).addClass('red')

})

})

3、效果演示

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>无标题文档</title>

<script src="js/jquery-1.4.4.js" type="text/javascript"></script>

<script>

$(document).ready(function(){

$("td").click(function(){

alert("第"+($(this).index()+1)+ "个td")

})

})

</script>

</head>

<body>

<table width="200" border="0" cellspacing="0" cellpadding="0">

<tr>

<td>ttttttt</td>

<td>ddddddd</td>

</tr>

<tr>

<td> </td>

<td> </td>

</tr>

<tr>

<td> </td>

<td> </td>

</tr>

</table>

</body>

</html>

晕 楼主好刁钻啊,按照你的意思

<table>

<tr>

<td>第1格</td>

<td>第1格</td>

<td>第2格</td>

</tr>

</table>

这段代码是一点都不能动了? 我做了段js代码,适合你的例子,也只有这种方法了!

<script type="text/javascript">

var firstname=document.getElementsByTagName("td")

firstname[0].style.backgroundColor="red"

firstname[1].style.backgroundColor="blue"

firstname[2].style.backgroundColor="yellow"

</script>

不过这段代码必须加在<table>...</table>后,不能加在<head>内,因为代码有作用必须在页面元素加载完毕后再执行才行,并且在实际中并适合用于大的网页,比如你的页面表格很多,td元素数组长度就很大,遍历时数组下脚值就是个大问题,还是你建议多辅助些css.