我使用的jQuery版本为jquery-3.3.1.js,下载地址:https://code.jquery.com/jquery-3.3.1.js
我使用的Chrome版本为 Version 63.0.3239.132 (Official Build) (64-bit)
给定一个表格如下图所示:
实现三个功能:
1、获取第二行第三列值(B3)
2、获取第三列所有的值(A3、B3、C3、D3、E3)
3、获取第三行所有的值(C1、C2、C3、C4)
代码如下:
<html>
<head>
<title>jQuery学习</title>
<!--表格处理-->
</head>
<body>
<table border="1" id="tbl">
<tr>
<th></th>
<th>第一列</th>
<th>第二列</th>
<th>第三列</th>
<th>第四列</th>
</tr>
<tr><td>第一行</td><td>A1</td><td>A2</td><td>A3</td><td>A4</td></tr>
<tr><td>第二行</td><td>B1</td><td>B2</td><td>B3</td><td>B4</td></tr>
<tr><td>第三行</td><td>C1</td><td>C2</td><td>C3</td><td>C4</td></tr>
<tr><td>第四行</td><td>D1</td><td>D2</td><td>D3</td><td>D4</td></tr>
<tr><td>第五行</td><td>E1</td><td>E2</td><td>E3</td><td>E4</td></tr>
</table>
<br>
<button type="button" id='btnGetValue'>获取第二行第三列值</button><br>
<button type="button" id='btnGetValue2'>获取第三列所有的值</button><br>
<button type="button" id='btnGetValue3'>获取第三行所有的值</button><br>
<script src="jquery-3.3.1.js"></script>
<script>
$(function(){
//目标1:获取第2行第3列的值
$('#btnGetValue').click(function(){
var val = $("#tbl tr:eq(2) td:eq(3)").html();
alert(val);
})
//目标2:获取第三列所有的值
$('#btnGetValue2').click(function(){
$("#tbl tr:gt(0)").each(function(){
alert($(this).children("td").eq(3).html());
})
/* 以下代码功能同上
$("#tbl tr").each(function(i){
if(i>=1){
alert($(this).children("td").eq(3).html());
}
})*/
})
//目标3:获取第三行所有的值
$('#btnGetValue3').click(function(){
$("#tbl tr:eq(3) td:gt(0)").each(function(){
alert($(this).html());
})
})
});
</script>
</body>
</html>
END