簡體   English   中英

JavaScript-單擊時查找行的第一個單元格值

[英]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> 

API和模式


演示

 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'>&nbsp;</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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM