我正在尝试实现一个 javascript,它将在单击时突出显示 html 表中的列。作为下面行突出显示的工作示例,我尝试将其与 table.columns 一起使用,但 table.columns 不存在。是有没有使用 jquery 突出显示 html 表中的列?
高亮行的工作代码: 表格突出显示 POC
<script>
function highlight() {
var table = document.getElementById('dataTable');
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
if (!this.hilite) {
this.origColor = this.style.backgroundColor;
this.style.backgroundColor = '#BCD4EC';
this.hilite = true;
}
else {
this.style.backgroundColor = this.origColor;
this.hilite = false;
}
}
}
}
</script>
<style>
table {
border-spacing: 0px;
}
td {
border: 1px solid #bbb;
padding: 0.2em;
}
</style>
</head>
<body>
<table id="dataTable">
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
</table>
</body>
</html>
最佳答案
您可以使用以下代码:
$('td').on('click', function() {
var $currentTable = $(this).closest('table');
var index = $(this).index();
$currentTable.find('td').removeClass('selected');
$currentTable.find('tr').each(function() {
$(this).find('td').eq(index).addClass('selected');
});
});
只需将它放在您的 JS 文件中,它就会独立地处理所有可用的表。如果您只想在特定表上使用它,只需将初始选择器更改为 $('#myTable td')
。
另外不要忘记添加 .selected{ background-color: #ace;
你的 css 文件中的类。
这是 working example .
干杯!
关于javascript - 如何使用 js 或 jquery 在单击时突出显示 html 表中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131000/