我試圖取得所有未點擊按鈕的行的值。例如,當我單擊第一行上的按鈕時,我想檢索沒有單擊的行的值。
var table = document.getElementById("all_department"); if (table != null) { for (var i = 0; i < table.rows.length; i++) { table.rows[i].onclick = function() { tableText(this); } } } function tableText(tableRow) { var myJSON = JSON.stringify(tableRow); console.log(myJSON); }
<table id="all_departments"> <thead> <th><button>click</button></th> <th>Departments</th> <th>Creation Date</th> <th>Name</th> </thead> <tbody class="bl"> <tr> <td><button>click</button></td> <td>Management</td> <td>2-3-2016</td> <td>client x</td> </tr> <tr> <td><button>click</button></td> <td>Sales</td> <td>25-6-2019</td> <td>client y</td> </tr> </tbody> </table>
P粉5613239752024-04-06 00:50:27
您可以監聽按鈕上的點擊處理程序,取得點擊按鈕的父 tr,然後取得同級按鈕。
一旦獲得所有兄弟姐妹,我們就可以循環它們並形成我們的結果字串。
請參考下面的程式碼
const allBtns = document.querySelectorAll('button'); allBtns.forEach(function(btn) { btn.addEventListener('click', function(e) { let elem = this.closest('tr'); const siblings = getSiblings(elem); const result = []; siblings.map(ele => { ele.querySelectorAll('td').forEach((e, i) => { if (i !== 0) { result.push(e.innerText); } }); }); console.log(result.join(',')); }) }); const getSiblings = function(e) { let siblings = []; if (!e.parentNode) { return siblings; } let sibling = e.parentNode.firstChild; while (sibling) { if (sibling.nodeType === 1 && sibling !== e) { siblings.push(sibling); } sibling = sibling.nextSibling; } return siblings; };
Departments | Creation Date | Name | |
---|---|---|---|
Management | 2-3-2016 | client x | |
Sales | 25-6-2019 | client y |