代码之家  ›  专栏  ›  技术社区  ›  Matt

从网格中的div类获取comp id

  •  1
  • Matt  · 技术社区  · 7 年前

    给定一个AG网格,我需要能够获得 comp-id 按tab键时,当前聚焦单元格中的数字。我目前在div类上有一个事件侦听器,但它给出了一个错误: cell.addEventListener is not a function

    我在试着得到答案 公司id 以下是:

    const cell = document.getElementsByClassName('ag-cell');
    cell.addEventListener("keydown", function(e) {
        if (e.key === "Tab") {
          console.log("ID", comp-id);
        }
    });
    

    链接到Plunkr: Link

    更新:

    我能拿到 公司id 通过从div中获取属性来获取值:

    if(e.key === "Tab"){
      let lastCell = cell.attributes[2].value;
    }
    

    尽管我注意到它似乎没有得到第176个单元格之后的值,尽管数据网格中还有更多。

    1 回复  |  直到 7 年前
        1
  •  0
  •   dance2die    7 年前

    getElementsByClassName 返回类型的序列 HTMLCollection .

    也就是说,它返回多个单元格。
    因此,您需要为每个项目添加一个事件侦听器(即使集合中只有一个项目)。

    ⚠️ 要知道 map 是属于数组的方法,因此需要首先将HTMLCollection的实例转换为数组(使用扩展语法或 Array.from )

    const cells = document.getElementsByClassName('ag-cell');
    [...cells].map(cell => (
      cell.addEventListener("keydown", function(e) {
          if (e.key === "Tab") {
            console.log("ID", comp-id);
          }
      })
    )