在 forEach 数组中使用索引

我有一个对象数组显示在表格中...我的目标是通过单击表中的某个特定项来访问该项。然后,我将能够添加/删除类并访问值,这最终是我需要做的。


这就是我陷入困境的地方...


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/


梦里花落0921
浏览 198回答 1
1回答

慕尼黑8549860

而不是搞砸索引等。您可以将事件处理程序附加到事件处理程序中,并且只在事件处理程序中引用。我还清理了您添加的tr。tre.targetconst myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}]&nbsp; &nbsp; &nbsp; myArray.forEach((item, index) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let row = document.createElement("tr");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let cell = document.createElement("td");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cell.innerHTML = item.number;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.appendChild(cell);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cell = document.createElement("td");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cell.innerHTML = item.otherNumber;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.appendChild(cell);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('myElementID').appendChild(row);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.addEventListener('dblclick', (e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(e.target);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });<table id="myElementID">&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th id="heading">Heading1</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th id="anotherHeading">Heading2</th>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; </table>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript