jquery tabel 获取点击前tr行数 并操作颜色
html+js
<!DOCTYPE> <html> <head> <title>table</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js "></script> <style type="text/css"> table {border: 1px solid black; /*修正单元格之间的边框不能合并*/border-collapse : collapse;width: 400px;} table td {border: 1px solid black;} table th {border: 1px solid black;} tbody th {background-color: #A3BAE9;} .trRed{ background-color:Red;} .trSP{background-color:Blue;} </style> <script type="text/javascript"> var tableTRS, tableTDs; $(function () { tableTRS = $("tr"), tds = $("td"); tds.click(tdclick); }); function tdclick() { var thisInfo = $(this), hang = thisInfo.parent("tr").prevAll(), //prevAll()表示这个tr前面有多少个tr lie = thisInfo.prevAll().length + 1; tableTRS.removeClass("trRed").removeClass("trSP"); $(hang).addClass("trRed"); $("tr:gt(" + hang.length + ")").addClass("trSP"); hang = hang.length + 1; alert("第" + hang + "行" + "第" + lie + "列"); } </script> </head> <body> <table border="1px" width="300" id="table1"> <tr> <td>1</td> <td>2</td> <td>q</td> <td>t</td> </tr> <tr> <td>a</td> <td>2</td> <td>q</td> <td> y</td> </tr> <tr> <td>b</td> <td>2</td> <td>3</td> <td>b</td> </tr> <tr> <td>c</td> <td>2</td> <td>q</td> <td>4</td> </tr> </table> </body> </html>
方法2:
$("tr").each(function (index) { $(this).click(function () { alert(index);//index是从0开始 所以实际的行数+1 }); });
图: