首页 > 解决方案 > 将颜色应用于单击的表格行

问题描述

当我点击表格行时,我有这个功能来检测。我希望它把点击的行变成某种颜色,并从所有其他行中删除活动类。目前它只是让我点击红色的每一行而不从其他行中删除颜色。

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>

标签: javascript

解决方案


这应该有效。请注意 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');
}

推荐阅读