![](/img/trans.png)
[英]JavaScript Getting second <td> cell value when clicked on a button on the same row
[英]JavaScript - Find row's first cell value when clicked
我有下表,其中每行有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
您可以使用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>
事件委托僅使用一個事件偵聽器即可有效控制表中每個標記的click事件。
event.target
引用被單擊的按鈕, event.currentTarget
引用該表。
.contains()
以獲取單擊的按鈕所在的行。
.return
matches()
確定event.target是否具有名為.return
的類。
var T = document.querySelector('.Table1'); T.addEventListener('click', function(e) { var out = document.getElementById('out'); // Clicked tag (ie a button.return) var tgt = e.target; // Tag registered to event (ie 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.