如何从与我按下的按钮位于同一行的单元格中获取值

How can I get the value from a cell which is in the same row as the button I am pressing

因此,当我按下同一行的按钮时,我试图获取 USUARIO 列的值: For example, if I was about to press the first button, it should give me 3 as a result

在我的代码中我有这个:

function(response) {
                        var t = "";
                        var tr = "";
                        tr += "<thead>";
                        tr += "<th>USUARIO</th>";
                        tr += "<th>FECHA INICIO</th>";
                        tr += "<th>FECHA FIN</th>";
                        tr += "<th>TIPO EMERGENCIA</th>";
                        tr += "<th>LOCALIZACIÓN</th>";
                        tr += "<th>DESACTIVADOR</th>";
                        tr += "</thead>";
                        tr +=  '<tbody id="tbody' +  i +">';
                        tr += '<td class= "OIDCELL">' + response[i].usuario_oid + "</td>";
                        tr += "<td>" + response[i].fechainicio + "</td>";
                        tr += "<td>" + response[i].fechafin + "</td>";
                        tr += "<td>" + response[i].tipoemergencia_tipo
                                + "</td>";
                        tr += "<td>" + enlace + "</td>";
                        if (response[i].desactivador == 0){
                            tr += '<td> <button type="button" onclick="cambiarDesactivador()">Desactivar</button></td>';
                        }else{
                            tr += "<td>" + response[i].desactivador + "</td>";
                        }
                        
                        tr += "</tr>";
                        tr += "</tbody>";
                        }
                        t += tr;
                        document.getElementById("historicoUser").innerHTML += t;
                    }

那么我可以通过什么方式获取按下按钮同一行的USUARIO列的值?

提前致谢!

您可以直接将列中显示的值 response[i].usuario_oid 传递给按钮的 onClick 函数

示例:cambiarDesactivador(response[i].usuario_oid)

对代码的一些评论,其中有很多错误:

  1. function(response) {...} 不是有效的函数声明或表达式
  2. t 变量似乎多余
  3. 不要混淆双引号和单引号的语义。 javascript 使用单引号,HTML 使用双引号(见下文)
  4. 所有 += 都是低效的,只需创建一个字符串并将其分配给 tr,例如:
tr = '<thead>' +
     '<th>USUARIO</th>' +
     '<th>FECHA INICIO</th>' +
     ...
     '<tbody id="tbody' +  i + '">' +
     ...

要获取被单击的按钮的行,获取对按钮的引用然后使用 closest to get the tr ancestor. Table rows 有一个 cells 集合,第一个单元格是索引 0等

所以从侦听器传递this,向上移动然后获取第一个单元格的内容,例如

function getFirstCellContent(el) {
  let row = el.closest('tr');
  console.log(row.cells[0].textContent);
}
table {
 border-left: 1px solid #999999;
 border-top: 1px solid #999999;
 border-collapse: collapse;
}
th, td {
 border-right: 1px solid #999999;
 border-bottom: 1px solid #999999;
}
<table>
  <tr><td>One<td><button onclick="getFirstCellContent(this)">Click me</button>
  <tr><td>Two<td><button onclick="getFirstCellContent(this)">Click me</button>
  <tr><td>Three<td><button onclick="getFirstCellContent(this)">Click me</button>
</table>