简体   繁体   中英

Highlight table row by clicking cellof first column

new to javascript. What i want this program to do is if the first cell of each row is clicked, I want to highlight that row. If any other cell is clicked, I want to highlight that one cell. I think my logic is correct, if I can get the cell index, I can highlight the correct cell(s) but the number that keeps getting passed into my highlight function is 9. Not sure where I'm going wrong.

window.onload = function() {
  var cells = document.getElementsByTagName("td");
  var theads = document.getElementsByTagName("th");

  for (var i = 0; i < cells.length; i++) {
    cells[i].addEventListener("click", function() {
      highlightCell(i);
    });
  }

    function highlightCell(x) {
      //alert(x + " clicked");
      if (x == 0) {
        //highlight table cells 0,1,2 lightBlue
        //highlight others to white
      } else if (x == 3) {
        //highlight table cells 3,4,5
        //highlight others to white
      } else if (x == 6) {
        //highlight table cell 6,7,8
        //highlight others to white
      } else {
        //highlightCell single table cell clicked
        //hihglight others to white
      }
    }

  }
}

Change var i to let i . let addresses a Javascript problem with references and closures. Reference: https://stackoverflow.com/a/30479554/5351510

for (let i = 0; i < cells.length; i++) {
  cells[i].addEventListener("click", function() {       
    highlightCell(i);
  });
}

Gordon's answer will work, but let is an addition to the standards that may not be supported in all browsers. You can rewrite your functionality like this for closure and broader compatibility:

var cells = document.getElementsByTagName("td");
var theads = document.getElementsByTagName("th");

for (var i = 0; i < cells.length; i++) {
  (function(){
    var x=i
    cells[x].addEventListener("click", function() {
      highlightCell(x);
  }());
}

function highlightCell(x){
  console.log(x);
}

This is a typical scope problem that can be solved with a closure. Basically the variable i in your 'for' is accessing the i value of the outer scope which is the last number the i got from the 'for'. To solve this you need to bind the variable within each function to a separate unique scope so it doesn't access the outer scope.

Check this guide to scopes and closures: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md .

return a function that returns your function so you create a new scope.

function highlightCell(i) {
  return function() { ...do your highlight thing that uses i... };
}

cells[i].addEventListener("click", function() {
  highlightCell(i);
});

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