JavaScript问题:表格中按钮的rowIndex属性无法正常工作
嘿,我来帮你搞定这个问题~你的核心问题是函数里的this指向不对,导致拿不到正确的行索引,我们一步步来修正:
问题分析
当你直接写onclick='getmylocation();'时,函数getmylocation里的this指向的是全局的window对象,而不是按钮所在的<tr>元素,所以this.rowIndex根本取不到你想要的行号。另外,原代码里获取<td>的方式也有问题——document.getElementById('table1').getElementsByTagName("td")会拿到表格里所有的<td>(包括按钮所在的那个),用行索引去取的话会拿到错误的单元格。
解决方案
我们可以通过call()方法把按钮的上下文传递给函数,同时调整获取目标单元格的逻辑,确保拿到对应行的第一个<td>内容:
修正后的JavaScript代码
function getmylocation() { // 先找到当前按钮所在的<tr>行 const currentRow = this.parentElement.parentElement; // 获取该行的第一个<td>的文本内容 const targetText = currentRow.getElementsByTagName("td")[0].innerText; // 找到table2的第一个<td>并替换内容 const table2FirstCell = document.getElementById('table2').getElementsByTagName("td")[0]; table2FirstCell.innerText = targetText; }
修正后的HTML代码
<table id='table1'> <tr> <td> row1, col1</td> <td> <button onclick='getmylocation.call(this);'>Click</button></td> </tr> <tr> <td> row2, col1</td> <td> <button onclick='getmylocation.call(this);'>Click</button></td> </tr> </table> <br> <table id='table2'> <tr> <td> empty1</td> <td>empty2</td> </tr> </table>
为什么这样能行?
getmylocation.call(this)里的this在onclick事件中指向的是当前点击的<button>元素,通过call()把这个上下文传递给getmylocation函数,函数里的this就变成了按钮本身。- 然后通过
this.parentElement.parentElement找到按钮所在的<tr>(按钮的父元素是<td>,<td>的父元素就是<tr>),再取该行的第一个<td>内容,这样就准确拿到了对应行的文本。 - 最后找到
table2的第一个<td>,替换它的内容即可。
另外,你也可以用更简洁的方式,比如直接在onclick里把行元素传进去:
<button onclick='getmylocation(this.parentElement.parentElement);'>Click</button>
对应的JS改成:
function getmylocation(row) { const targetText = row.getElementsByTagName("td")[0].innerText; document.getElementById('table2').getElementsByTagName("td")[0].innerText = targetText; }
这种方式可读性可能更强一些,看你个人偏好~
内容的提问来源于stack exchange,提问作者jimmune
相关产品推荐
相关产品推荐

