简体   繁体   中英

Toggle row color red and table color white on click with pure javascript (no jquery)

I'm trying to duplicate the following JSFiddle in pure javascript without relying on jquery or other methods.

 $('table tr').each(function(a,b){ $(b).click(function(){ $('table tr').css('background','#ffffff'); $(this).css('background','#ff0000'); }); }); 
 <table> <tr> <td>data</td> <td>data</td> </tr> <tr> <td>data</td> <td>data</td> </tr> </table> 

The first click highlights a row, the second click highlights the next selected row and removes the highlight from the previous row. Also, I've tried implementing this code in my work but it wouldn't work at all and provides 0 error messages to give me a clue as to what is going on. Copy/pasting this fiddle into a new one does not reproduce the results and this seems to be a common theme while trying to track down an answer to this problem. I've searched all over stackoverflow and haven't been able to find a working solution that relies only on css, javascript, and/or html.

Use [].forEach.call to iterate tr elements. Use of Function#call is needed as document.querySelectorAll does not return Array .

 [].forEach.call(document.querySelectorAll('table tr'), function(el) { el.addEventListener('click', function() { [].forEach.call(document.querySelectorAll('table tr'), function(el) { el.style.background = '#fff'; }); this.style.background = '#f00' }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table border="1" cellspacing="1" width="100%" id="table1"> <tr> <th>Column1</th> <th>Column2</th> <th>Column3</th> <th>Column4</th> <th>Column5</th> </tr> <tr> <td>data</td> <td>data</td> <td>data</td> <td>data</td> <td>data</td> </tr> <tr> <td>data</td> <td>data</td> <td>data</td> <td>data</td> <td>data</td> </tr> <tr> <td>data</td> <td>data</td> <td>data</td> <td>data</td> <td>data</td> </tr> <tr> <td>data</td> <td>data</td> <td>data</td> <td>data</td> <td>data</td> </tr> </table> 

https://jsfiddle.net/M4V3R1C8/7L2typ5t/1/ This script allows you to do exactly what I was looking for. The only downside is that you cannot activate the top row. Also, I can't seem to change the .selected name as it will stop working. Good enough for now, onto the next problem.

function selected(){
    var index,
      table = document.getElementById("dps");
  for(var i = 1; i < table.rows.length; i++) {
        table.rows[i].onclick = function() {
        if(typeof index !== "undefined"){
          table.rows[index].classList.toggle("selected");
      }
      console.log(typeof index);
      index = this.rowIndex;
      this.classList.toggle("selected");
      console.log(typeof index);
    };
  }
}
selected();

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