简体   繁体   English

如果表格是动态生成的,如何在点击时更改html单元格的颜色?

[英]How do I change an html cell's color on click, if the table is generated dynamically?

 function drawTable() { var table = document.getElementById("myTable"); var input = prompt("Insert height (in number of cells)"); var a = +input; var input2 = prompt("Insert width (in number of cells)"); var b = +input2; for (var i = 0; i < a; i++) { var row = table.insertRow(i); for (var j = 0; j < b; j++) { var cell = row.insertCell(j); }; }; }; 

I can't for the life of me figure out how to add a onClick event that would change the color of a cell. 我一辈子都想不起来如何添加一个onClick事件来改变单元格的颜色。 Do I create a new function in JavaScript and add an onClick event to the table element? 是否要在JavaScript中创建新函数并将onClick事件添加到表元素? That's what I did, but it doesn't seem to work. 那是我所做的,但似乎不起作用。

  function changeColor() { var td = document.getElementsById("myTable").getElementsByTagName("td"); td.style.backgroundColor = "red"; } 

for (var j = 0; j < b; j++) {

  var cell = row.insertCell(j);
  cell.addEventListener("click", changeColor.bind(cell), false);
};

function changeColor(e) {
      this.style.backgroundColor = "red";
}

Should do the trick. 应该做到的。 Every cell gets an onclick handler set in the for loop. 每个单元格都会在for循环中设置一个onclick处理程序。 Bind passes the reference of the cell to the changeColor function. Bind将单元格的引用传递给changeColor函数。 The function can address the cell by using this . 该函数可以使用this寻址单元格。

For some situations, the answer suggested by Mouser work well. 在某些情况下, Mouser建议的答案很好用。 But if consider a situation taking your example of table creation based on number of rows and columns, then adding eventlistener to each cell doesn't sound a good approach. 但是,如果考虑一种情况,以基于行和列数的表创建示例为例,那么向每个单元格添加事件侦听器似乎不是一个好方法。 Suppose at initial user requested for 10X10 table. 假设最初的用户要求提供10X10表格。 At that moment, eventlistener is added to each cell. 那时,事件侦听器已添加到每个单元中。

But what if at some later point of time, more rows/columns are added dynamically. 但是,如果在以后的某个时间点动态添加更多的行/列,该怎么办? In that situation, only thing you will left with is to add event listeners. 在这种情况下,剩下的就是添加事件侦听器。

Better approach is to understand the term 更好的方法是理解术语

Event Delegation 活动委托

In this approach, you add event listener to parent and just listen to event bubbled up(default behavior) by the child elements.In that case you dont have to be worry about dynamically created cells and adding event listeners to those. 在这种方法中,您将事件侦听器添加到父级,然后仅侦听子元素冒泡的事件(默认行为)。在这种情况下,您不必担心动态创建的单元格并向其添加事件侦听器。

You can take a look on working sample with Event Delegation approach on your code at below link: 您可以在下面的链接上通过代码使用事件委托方法来研究工作示例:

http://jsfiddle.net/zL690Ljb/1/ http://jsfiddle.net/zL690Ljb/1/

function drawTable() {

 var table = document.getElementById("myTable");
 table.addEventListener("click", changeColor);

 var input = prompt("Insert height (in number of cells)");
 var a = +input;
 var input2 = prompt("Insert width (in number of cells)");
 var b = +input2;

 for (var i = 0; i < a; i++) {
    var row = table.insertRow(i);
    for (var j = 0; j < b; j++) {

    var cell = row.insertCell(j);
  //cell.addEventListener("click", changeColor.bind(cell), false);
};
};
};

function changeColor(event) {
    if (event.target && event.target.tagName && (!event.target.tagName.match(/table|th|tr|tbody|thead/i)) )
    {
      var element = event.target;
      while (element && element.parentElement)
      {
          if(element.tagName=='TD'){
               element.style.backgroundColor = "red";
               break;
          }
          else
          {
             element = element.parentElement;
          }
      }
    }
}

drawTable();

I hope Mouser will agree on this. 我希望Mouser对此表示同意。 Thanks! 谢谢!

Inside the for you can add the onclick event for each cell: 在for内,您可以为每个单元格添加onclick事件:

for (var i = 0; i < a; i++) {
    var row = table.insertRow(i);
    for (var j = 0; j < b; j++) {
      var cell = row.insertCell(j);
      cell.onclick = function(){
        changeColor(this);  
      }
    };
};

Then the changeColor will be as following: 然后changeColor将如下所示:

function changeColor(cell) {
    cell.style.backgroundColor = "red";

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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