如何用原生JavaScript点击表格行任意位置获取指定数字
实现表格行任意点击获取对应unstakeIdx值
示例HTML结构
<table> <tr class="newEle"> <td>第一行内容1</td> <td class="unstakeIdx">0</td> <td>第一行内容2</td> </tr> <tr class="newEle"> <td>第二行内容1</td> <td class="unstakeIdx">1</td> <td>第二行内容2</td> </tr> </table>
原生JavaScript实现代码
// 选中所有带newEle类的表格行 const targetRows = document.querySelectorAll('.newEle'); // 为每一行绑定点击事件 targetRows.forEach(row => { row.addEventListener('click', function() { // 在当前点击的行内查找unstakeIdx元素 const idxCell = this.querySelector('.unstakeIdx'); if (idxCell) { // 获取并处理索引值(trim去除空格,parseInt转为数字) const unstakeIdx = parseInt(idxCell.textContent.trim(), 10); // 这里可以替换成你需要的后续操作,比如打印、传参等 console.log('当前行的unstakeIdx:', unstakeIdx); } }); });
关键逻辑说明
- 直接给整个
<tr>绑定点击事件,而非仅绑定到unstakeIdx单元格,这样点击行内任意位置都会触发 - 使用
this.querySelector('.unstakeIdx')限定查找范围为当前点击的行,避免获取到其他行的索引值 - 通过
textContent.trim()清理文本内容的多余空格,再用parseInt转为数字类型(如果只需要字符串,可省略parseInt步骤)
内容的提问来源于stack exchange,提问作者Pro Girl
相关产品推荐
相关产品推荐

