我试图获取所有未单击按钮的行的值。例如,当我单击第一行上的按钮时,我想检索没有单击的行的值。
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>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以监听按钮上的单击处理程序,获取单击按钮的父 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; };