如何获取带有相同class的表格行中被点击行的第二个td值
没问题!要实现点击表格里的行就能获取该行第二个单元格的数值,这里有两种实用的方案,你可以根据自己的项目技术栈来选:
首先先补全你给出的表格结构(确保HTML规范可运行):
<table> <thead> <tr> <th>Qty</th> <th>Price</th> <th>Total</th> </tr> </thead> <tbody> <tr class="myclass"> <td>3</td> <td>10</td> <td>30</td> </tr> <tr class="myclass"> <td>2</td> <td>15</td> <td>30</td> </tr> </tbody> </table>
方案1:原生JavaScript(无需依赖第三方库)
这种方法适合不想引入额外库的项目,直接用浏览器原生API实现:
// 选中所有带有myclass类的表格行 const targetRows = document.querySelectorAll('.myclass'); // 给每一行绑定点击事件 targetRows.forEach(row => { row.addEventListener('click', function() { // 获取当前行的第二个td元素(索引从0开始,所以第二个是1) const priceValue = this.querySelectorAll('td')[1].textContent; // 这里可以把数值用于任何你需要的操作,比如打印到控制台或者显示在页面上 console.log('点击行的价格是:', priceValue); }); });
解释:
querySelectorAll('.myclass')会选中所有符合类名的行;- 循环给每行添加点击事件,点击时
this就代表被点击的那一行; - 通过
this.querySelectorAll('td')[1]定位到该行的第二个单元格,再用textContent取出里面的文本值。
方案2:jQuery(如果项目已引入jQuery库)
如果你的项目已经在用jQuery,那代码会更简洁:
// 给所有.myclass的行绑定点击事件 $('.myclass').on('click', function() { // 找到当前行的第二个td,取出文本值 const priceValue = $(this).find('td').eq(1).text(); console.log('点击行的价格是:', priceValue); });
解释:
$('.myclass').on('click', ...)给目标行绑定点击事件;$(this)指代被点击的行,find('td')找到该行所有单元格;eq(1)选中第二个单元格(索引从0开始),text()获取里面的文本内容。
如果需要把获取到的数值展示在页面的某个元素里,比如一个id为price-display的div,只需要把console.log换成:
// 原生JS写法 document.getElementById('price-display').textContent = priceValue; // jQuery写法 $('#price-display').text(priceValue);
内容的提问来源于stack exchange,提问作者Deepak M
相关产品推荐
相关产品推荐

