0

我在表格中显示了一组对象...我的目标是通过单击表格中的项目来访问数组中的特定项目。然后我就可以添加/删除类并访问这些值,这最终是我需要做的。

这就是我被困的地方......

myArray.forEach((item, index) => {
// Sort through array, render to DOM
  document.getElementById('myElementID').innerHTML +=
    '<tr>' +
    '<td>' +
    item.thing +
    '</td>' +
    '<td' +
    item.thing2 +
    '</td>' +
    '</tr>';

// Completely stuck... I've added an event listener to each table row.

  addEventListener('dblclick', () => {
    console.log(//I want to log the index of the item I just clicked on);
  });
});

请原谅我,如果这很容易,或者我要解决这一切都错了,但我对这一切都很陌生,我无法以谷歌有帮助的方式来组织我的问题。

提前致谢。

编辑 - 一些 html 根据要求...

      <table id="myElementID">
        <tr>
          <th id="heading">Heading1</th>
          <th id="anotherHeading">Heading2</th>
        </tr>
      </table>

再次编辑(对不起)......和一个JS小提琴。您会看到它记录了两个索引,而不仅仅是我单击的那个。https://jsfiddle.net/c4pd5wmg/4/

4

1 回答 1

0

而不是弄乱索引等。您可以将事件处理程序附加到事件处理程序中tr并仅e.target在事件处理程序中引用。我还清理了你添加的 tr。

const myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}]

      myArray.forEach((item, index) => {
    
          let row = document.createElement("tr");
          let cell = document.createElement("td");
          cell.innerHTML = item.number;
          row.appendChild(cell);
          
          cell = document.createElement("td");
          cell.innerHTML = item.otherNumber;
          row.appendChild(cell);
    
          document.getElementById('myElementID').appendChild(row);
        
          row.addEventListener('dblclick', (e) => {
             console.log(e.target);
          });
        });
<table id="myElementID">
        <tr>
          <th id="heading">Heading1</th>
          <th id="anotherHeading">Heading2</th>
        </tr>
      </table>

于 2020-05-19T21:23:26.267 回答