我有下表,其中每行有4个单元格,最后一个单元格上有一个按钮:
<table class='Table1'>
<tr>
<td>
ABC
</td>
<td>
DEF
</td>
<td>
GHI
</td>
<td>
<button class='return'>return</button>
</td>
</tr>
<tr>
<td>
JKL
</td>
<td>
MNO
</td>
<td>
PQR
</td>
<td>
<button class='return'>return</button>
</td>
</tr>
</table>
单击按钮后,我想使用Javascript
(否jquery
)查找同一行的第一个单元格值。例如,如果我单击第一行上的return
按钮,它将返回ABC
答案 0 :(得分:0)
您可以使用函数closest
来获取元素tr
,然后使用函数querySelector
来获取第一个元素td
。
Array.prototype.forEach.call(document.querySelectorAll('button'), function(b) {
b.addEventListener('click', function() {
console.log(this.closest('tr').querySelector('td').textContent.trim());
});
})
<table class='Table1'> <tr> <td> ABC </td> <td> DEF </td> <td> GHI </td> <td> <button class='return'>return</button> </td> </tr> <tr> <td> JKL </td> <td> MNO </td> <td> PQR </td> <td> <button class='return'>return</button> </td> </tr></table>
答案 1 :(得分:0)
HTMLTableElement.rows 和 HTMLTableRowElement.cells 以便于操作表格组件。
Event Delegation ,仅使用一个事件侦听器即可有效地控制表中每个标签的click事件。
event.target
引用被单击的按钮, event.currentTarget
引用表格。
.contains()
以获得被单击的按钮所在的行。
matches()
来确定 event.target 是否具有名为.return
的类。
var T = document.querySelector('.Table1');
T.addEventListener('click', function(e) {
var out = document.getElementById('out');
// Clicked tag (i.e. a button.return)
var tgt = e.target;
// Tag registered to event (i.e. table.Table1)
var cur = e.currentTarget;
// A HTMLCollection of every <tr> in .table1
var Rows = cur.rows;
// Declare blank string;
var txt = "";
/*
if clicked tag is NOT .Table1 AND it has class .return...
*/
if (tgt !== cur && tgt.matches('.return')) {
/*
Begin count at 0; keep counting until the last row;
increment cont by 1
*/
for (let i = 0; i < Rows.length; i++) {
// if this row has the clicked button as a descendant...
if (Rows[i].contains(tgt)) {
// Get the text of that row's first cell
txt = Rows[i].cells[0].textContent;
}
}
// Set the value of output#out to extracted text
out.value = txt;
}
});
table,
td {
border: 3px solid #000;
}
#out {
display: block
}
<output id='out'> </output>
<table class='Table1'>
<tr>
<td> ABC </td>
<td> DEF </td>
<td> GHI </td>
<td> <button class='return'>return</button> </td>
</tr>
<tr>
<td> JKL </td>
<td> MNO </td>
<td> PQR </td>
<td> <button class='return'>return</button> </td>
</tr>
<tr>
<td> HHH </td>
<td> DEF </td>
<td> GHI </td>
<td> <button class='return'>return</button> </td>
</tr>
<tr>
<td> 123 </td>
<td> DEF </td>
<td> GHI </td>
<td> <button class='return'>return</button> </td>
</tr>
<tr>
<td> XYZ </td>
<td> DEF </td>
<td> GHI </td>
<td> <button class='return'>return</button> </td>
</tr>
<tr>
<td> XXX </td>
<td> DEF </td>
<td> GHI </td>
<td> <button class='return'>return</button> </td>
</tr>
</table>