javascript - 将颜色应用于单击的表格行
问题描述
当我点击表格行时,我有这个功能来检测。我希望它把点击的行变成某种颜色,并从所有其他行中删除活动类。目前它只是让我点击红色的每一行而不从其他行中删除颜色。
html:
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr")[0];
tbody.onclick = function (e) {
e = e || window.event;
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
tbodyRows.classList.remove('active');
target.classList.add('active');
}
js:
<table id="data">
<thead>
<tr>
<th class="number" style="text-align:center">#</th>
<th class="time" style="text-align:center">time</th>
<th class="artist">artist</th>
<th class="song">song</th>
</tr>
</thead>
<tbody id="song-data"></tbody>
</table>
解决方案
这应该有效。请注意 tBodyRows 现在如何引用所有表行(删除[0]
)以及我们如何使用 迭代它forEach()
。
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr");
tbody.onclick = function (e) {
e = e || window.event;
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
Array.from(tbodyRows).forEach(elem => {
elem.classList.remove('active')
})
target.classList.add('active');
}
推荐阅读
- php - React:创建输入的函数
- theorem-proving - 如何执行所有共享一个多元普遍量化假设的多个存在消除?
- php - 为什么 PHP 脚本在调试时有时会在 index.php 开头重新启动?
- java - 如何为同一个属性节点添加多个约束违规?
- python - 在 Tensorflow Federated 中使用 'accuracy' 获得 'TypeError: Caught exception'
- angularjs - 测试内部调用异步方法的函数
- python - 熊猫数据框根据另一个字段的条件更改值
- java - JAXBException: SaveButton 及其任何超类对此上下文都是已知的
- swift - 在内容大小之前设置 UICollectionViewCell 大小
- ios - 为什么点击提交后文字消失?