javascript 将 addEventListener 添加到单击的表格单元格以更改颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3740650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:05:38  来源:igfitidea点击:

Adding addEventListener to a clicked table cell to change the color

javascriptaddeventlistener

提问by cameron213

I am creating a dynamic table of three columns and multiple rows. I want to be able to click the last cells in each row and have the row be selected showing a certain color. I am trying to do this as well as make sure that if another cell is selected already it will deselect. I am having a few issues not sure exactly what to do. I can create an onclick alert message that works, however no success with the bg color. Any suggestions are helpful. Function createCell should be where this is addressed.

我正在创建一个三列多行的动态表。我希望能够单击每行中的最后一个单元格并选择显示特定颜色的行。我正在尝试这样做,并确保如果已经选择了另一个单元格,它将取消选择。我有几个问题不确定该怎么做。我可以创建一个有效的 onclick 警报消息,但是 bg 颜色没有成功。任何建议都是有帮助的。函数 createCell 应该是解决这个问题的地方。

<html>
<br/><br/></p>
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
 <tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>

 </table>
<p></center></p>
<script type="text/javascript" language="javascript">

 function appendRow(){


var names = ["Paul", "Mike", "Linda"];
var ages = ["16", "23", "44"];
var male_female = ["M", "M", "F"];
var tbl = document.getElementById('my_table'); // table reference
// append table row
var id;
var z=1;
for(k=0;k<names.length;k++){    
var row = tbl.insertRow(tbl.rows.length);


    var j = tbl.rows.length - 2;
    for (var i=0;i<tbl.rows[0].cells.length;i++) {
        id=z++;
          var cell_text = '';
          if (i == 0) {
                 cell_text = names[j];
          } else if (i == 1) {
                 cell_text = ages[j];
          } else if (i == 2) {
                 cell_text = male_female[j];
          }
        createCell(id, row.insertCell(i), cell_text, 'row');

    }


  }


}

function createCell(id, cell, text, style){

var div = document.createElement('div'); // create DIV element

var txt = document.createTextNode(text); // create text node
if(id % 3 == 0)
{
          cell.setAttribute('onclick', 'alert("hello")');    //for testing purposes
      cell.addEventListener("click", clickCell, false);
}
div.appendChild(txt);                    // append text node to the DIV
div.setAttribute('class', style);        // set DIV class attribute
div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
cell.appendChild(div);            // append DIV to the table cell
}

  function clickCell()
 {
if(e)
  e.setAttribute("bgColor","purple");

 if(e != this){
    e = this;
    e.setAttribute("bgColor","blue");
 }else{
   e = null;
  }
 }      





 </script>
<BODY onload="appendRow()">

<style>
table#my_table{border-collapse:collapse;}
 table#my_table td{width:50px;height:27px;border:1px solid #D3D3D3;font-size:10pt;text-align:center;padding:0;}
  .append_row{background-color:#FFD6D6;border:1px #ccc solid;}
 </style>
 </body>
 </html> 

回答by Anurag

Modify the clickCellmethod to:

修改clickCell方法为:

function clickCell(e) {
    // clear the background of all rows
    var rows = document.getElementById('my_table').rows;
    for(var i = 0; i < rows.length; i++) {
        rows[i].style.backgroundColor = '';
    }
    // set background of clicked row
    this.style.backgroundColor = 'purple';
}

See an example.

请参阅示例

回答by Vinay B R

In createCell change cell.setAttribute('onclick', 'alert("hello")');to cell.setAttribute('onclick', 'alert("hello");this.parentNode.setAttribute("bgcolor", "purple")');

在 createCell 更改cell.setAttribute('onclick', 'alert("hello")');cell.setAttribute('onclick', 'alert("hello");this.parentNode.setAttribute("bgcolor", "purple")');

回答by cameron213

Figured out that if I set the clickcell function to the following, it will clear all cells that are colored. I thought I could call "this.style.backgroundColor" to change the cell color and then clear that cell with a "row.style.backgroundColor" turns out I was wrong.

发现如果我将 clickcell 函数设置为以下内容,它将清除所有着色的单元格。我以为我可以调用“this.style.backgroundColor”来更改单元格颜色,然后使用“row.style.backgroundColor”清除该单元格,结果我错了。

function clickCell(e) {
var tr = document.getElementById('my_table').rows;

for(i=0;i<tr.length;i++)
{
    for(k=0;k<tr[i].cells.length;k++)
    {
        tr[i].cells[k].style.backgroundColor = "";
    }
}   
this.style.backgroundColor = "blue";
}