简体   繁体   中英

Apply color to clicked table row

i have this function to detect when i click on a table row. I want it to turn the clicked on row a certain colour and remove the active class from all other rows. Currently it just makes every row i click on red without removing the colour from the other rows.

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>

This should work. Notice how tBodyRows now references all table rows (removed the [0] ) and how we iterate over it with 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');
}

You aren't possible to remove all the color from the other rows, because you are not deleting the other rows classes , you are only deleting one, I think a better way to show you is doing it, so I did this (I also think you can refactor a little more):

 const table = document.getElementById('data'); let tableBody = table.querySelector('tbody'); tableBody.onclick = function (e) { let tableRows = table.querySelectorAll('tbody tr'); let target = e.target.parentNode; while (target.nodeName !== 'TR') { target = target.parentNode; } tableRows.forEach((element) => { element.classList.remove('active'); }); target.classList.add('active'); }
 .active { background-color: red; }
 <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"> <tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> </tr> <tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM