javascript - 如何使子行列可点击?
问题描述
我有一个 HTML 表,其中有子行,我想让这些子行列可单击以执行特定操作。
我有父行,当我单击这些行时,将显示子行,其中有一个 column 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
。
推荐阅读
- wordpress - 寻找项目经理和报价请求系统的 WordPress 插件
- php - PHP - 管理 curl 输出
- c# - 编译器无法从包装的通用 IEnumerable 推断类型
- java - 使用 Recycler View 从列表中选择元素
- r - 使用应用函数制作多个图表并在标题中显示变量名称
- react-native - 在没有道具的情况下访问 React-Native 导航
- c - 在 n 个符号后放置 ' ' 的函数
- php - 如何存储和检索数据类型的图像:image/jpeg;base64?
- regex - 区分 .htaccess 中的两个重定向
- thingsboard - 来自时间戳打包的远程信息处理元素的解析错误