如何使用js或jquery突出显示html表中的列点击? [英] How to highlight a column in html table on click using js or jquery?
问题描述
我试图实现一个JavaScript,它将突出显示click.HTML表中的列的列。作为下面的行突出显示的工作示例,我试图使用table.columns相同但table.columns不存在。是有没有什么是突出显示在html表中使用jQuery的列?
I am trying to implement a javascript which will highlight the column in an html table on click.As the below working example for row highlight i tried to use the same with table.columns but table.columns doesn't exist.Is there any was to highlight the column in html table using jquery?
突出行的工作代码:
表突出显示POC
Working code for highlighting row: Table Highlight 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')
。
Just put this on your JS file and it will work on all available tables independently. In case you want to use it only on a specific table, just change the initial selector to $('#myTable td')
.
另外不要忘记添加 .selected {background-color:#ace; }
class在yor css文件中。
Also dont forget to add the .selected{ background-color: #ace; }
class in yor css file.
这是 working example 。
干杯!
这篇关于如何使用js或jquery突出显示html表中的列点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!