Returning Id of cell when clicked Javascript

时间:2018-03-08 23:34:23

标签: javascript html css html-table

I'm working on creating a table of cells that will change color when each cell is clicked on.

I've created the table and have unique Ids for 'td' element - how do I return the Id of the cell that was clicked so that I can change its background color?

Is it possible to do this with pure JS?

const grid = function makeGrid() {
    var body = document.getElementById('pixelCanvas');
    var tbl = document.createElement('table');
    var tblBody = document.createElement('tbody');

    for (let i = 0; i < 5; i++) {
        let row = document.createElement('tr');
        for (j = 0; j < 5; j++) {
            var cell = document.createElement('td')
            row.appendChild(cell)
            cell.setAttribute('id', 'makeId' + i + j);
        }
        tblBody.appendChild(row);
    }
    tbl.appendChild(tblBody);
    body.appendChild(tbl)
} 
grid();

3 个答案:

答案 0 :(得分:4)

不是在每个let numberOfTimes = reports.flatMap { internalDictsArray in internalDictsArray.value.filter { $0.value == "yourSearchString" } }.count 元素上设置事件侦听器,而是使用事件委派。

在表体上设置一个监听器。它会听到td元素的点击次数。使用事件对象的td属性来确定单击了哪个target。这是改变之一:

td

答案 1 :(得分:2)

您需要将click事件绑定到创建的cell

已编辑:使用活动委派

tblBody.addEventListener('click', (e)=>{
    if (e.target.nodeName.toUpperCase() === 'TD') {
       console.log(e.target.id)
       e.target.classList.add('bg');
    }
});

&#13;
&#13;
const grid = function makeGrid() {

  var body = document.getElementById('pixelCanvas');

  var tbl = document.createElement('table')
  var tblBody = document.createElement('tbody')

  tblBody.addEventListener('click', (e)=>{
      if (e.target.nodeName.toUpperCase() === 'TD') {
         console.log(e.target.id)
         e.target.classList.add('bg');
      }
  });

  for (let i = 0; i < 5; i++) {
    let row = document.createElement('tr')

    for (let j = 0; j < 5; j++) {
      var cell = document.createElement('td')
      cell.innerHTML = 'makeId' + i + j;
      row.appendChild(cell)
      cell.setAttribute('id', 'makeId' + i + j);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl)
}
grid();
&#13;
.bg {
  background-color: lightgreen;
}
&#13;
<div id="pixelCanvas">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

正如Randy所建议的,不是在每个TD上放置一个监听器,而是可以使用事件委托并将监听器放在一个合适的祖先上,即父表部分(tbody,thead,tfoot)或表本身。然后使用传递给侦听器的事件对象来获取事件的目标。如果它不是TD,请转到父节点,直到达到TD。

现在大多数浏览器都在使用Element.closest,但不是IE。所以你可能想要使用polyfill或简单的&#34; upTo&#34;这些用户的功能。

此外,您可以利用表和表部分元素的 insertRow insertCell 方法,而不是更长的 createElement 。最后,您可以组合创建元素并一次性附加它。

无论如何,像这样:

&#13;
&#13;
 
// Create a table with rows rows and cells columns
function genTable(rows, cells) {
  var table = document.createElement('table');
  // Create tbody and append in one go
  var tbody = table.appendChild(document.createElement('tbody'));
  tbody.addEventListener('click',highlightCell);
  var row, cell;

  // Use insert methods for less code
  for (var i=0; i<rows; i++) {
    row = tbody.insertRow();

  for (var j=0; j<cells; j++) {
      cell = row.insertCell();
      cell.textContent = 'row ' + i + ' cell ' + j;
    }
  }
  // Add entire table to document in one go, easier on host
  document.body.appendChild(table);
}

// Highlight cell that was clicked on
function highlightCell(e){
  // Remove highlight from all cells that have it
  document.querySelectorAll('.highlight').forEach(
    node => node.classList.remove('highlight')
  );
  // Add highlight to cell of td in which event occurred
  var cell = e.target.closest('td');
  cell.classList.add('highlight');
}

window.onload = function(){genTable(3, 3);};
&#13;
table {
  border-collapse: collapse;
  border-left: 1px solid #bbbbbb;
  border-top: 1px solid #bbbbbb;
}
td {
  border-right: 1px solid #bbbbbb;
  border-bottom: 1px solid #bbbbbb;
}
.highlight {
  background-color: red;
}
&#13;
&#13;
&#13;