我有一个 HTML 表格,其中有子行,我想让这些子行列可单击以执行特定操作。
我有父行,当我单击这些行时,会显示子行,其中有一列 col2
,当我单击该列时,应该对每个子行执行一些操作专栏。
我希望子行的 col2
可单击,以使用 JavaScript 和 HTML 显示更多信息。我不知道,但是在点击函数(onclick('col2')
)上类似的东西可能有帮助还是没有帮助??
var $container = $("#container");
var $row = $("#container table tbody tr");
// Loop through items in JSON data..
var $button = $("<button>" + 'abc' + "</button>");
$container.prepend($button);
var table = $("<table>");
table.append($("<tr><th>col1</th><th>col2</th></tr>"));
// Button click handler..
$button.on("click", function() {
for (var i = 0; i < 2; i++) {
// Replace row HTML..
//parent row
var row = $('<tr class="parent_row" ><td>' + 'data' + '</td>' + +'<td>' + "" + '</td></tr>');
table.append(row);
for (var j = 0; j < 2; j++) {
//child row
var row = $('<tr style="display: none"><td>' + "" + '</td>' + '<td>' + 'data' + '</td></tr>');
table.append(row);
}
}
$("#table").html(table);
$('.parent_row').click(function() {
$(this).nextUntil(".parent_row").toggle();
})
// Show table if it's not already visible..
});
table {
margin-top: 20px;
border: 1px solid silver;
width: 500px;
}
th {
text-align: left;
}
button {
margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="table">
</div>
</div>
最佳答案
要捕获表中任何列的点击,只需向该列中的所有单元格添加点击监听器即可:
const column2cells = document.querySelectorAll('#table tr>*:nth-child(2)');
for (const cell of column2cells) {
cell.addEventListener('click', function(event) {
console.log(`You clicked cell [${cell.cellIndex}, ${cell.parentElement.rowIndex}] with content "${cell.textContent}"`);
})
}
<table id="table">
<tr>
<th>Col 1</th>
<th>Col 2</th>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
作为日志输出的注释:记住 cellIndex
和 rowIndex
从 0
开始,而不是从 1
开始.
关于javascript - 如何使子行列可点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624933/