在JavaScript中,实现点击表格(<table>
)的一行使其变色的功能,通常涉及到以下几个基础概念:
<table id="myTable">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
.highlight {
background-color: yellow;
}
document.addEventListener('DOMContentLoaded', function() {
var tableRows = document.querySelectorAll('#myTable tr');
tableRows.forEach(function(row) {
row.addEventListener('click', function() {
// Remove highlight from all rows
tableRows.forEach(function(r) {
r.classList.remove('highlight');
});
// Add highlight to the clicked row
this.classList.add('highlight');
});
});
});
如果遇到样式未生效的问题,可以通过以下方式调试:
// 确保CSS类已正确添加
row.addEventListener('click', function() {
console.log(this.classList); // 查看点击行的类列表
this.classList.toggle('highlight');
});
通过上述步骤和代码示例,可以实现点击表格行变色的功能,并解决常见的实现问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云