D3.js v6.2 - 在监听器函数中获取数据索引 - selection.on ('click',监听器)

标签 d3.js

在以前的版本中,可以通过以下方式检索索引 i: selection.on("点击", function(d,i){...}

但是,这在最新版本中似乎不再起作用,因为第一个参数始终是事件对象。监听函数中如何获取数据的索引?

let data = [2,5,8,9]

d3.select("body").selectAll("p")
  .data(data)
  .enter()
  .append("p")
  .text(d=>d)
  .on("mouseover", function(e,d,i){
    //console.log(e); --> event
    console.log(d); 
    console.log(i);
    // i should be the index of the hovered element
  })
<script src="https://d3js.org/d3.v6.min.js"></script>

When a specified event is dispatched on a selected element, the specified listener will be evaluated for the element, being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget).

官方文档:https://github.com/d3/d3-selection/blob/v2.0.0/README.md#selection_on

最佳答案

可观察的 notebook关于 d3-selection 2.0 中的新功能建议使用局部变量来保留索引:

Listeners are no longer passed the selected element’s index (i) or siblings (nodes). These were rarely used, had confusing behavior if elements were re-selected, and could cause memory leaks. If you need them, bake them into the element’s data or use a local variable instead.

这可以通过以下方式轻松完成:

let data = [2,5,8,9]

const index = d3.local();            // Local variable for storing the index.

d3.select("body").selectAll("p")
  .data(data)
  .enter()
  .append("p")
    .text(d=>d)
    .each(function(d, i) {
      index.set(this, i);            // Store index in local variable.
    })
    .on("mouseover", function(e,d,i){
      console.log(d); 
      console.log(index.get(this));  // Get index from local variable.
    });
<script src="https://d3js.org/d3.v6.min.js"></script>

请注意,尽管为了清楚起见,上面的示例使用了对 .each() 的单独调用,但这也可以在对 .text() 的现有调用中完成为了简洁和性能。

关于D3.js v6.2 - 在监听器函数中获取数据索引 - selection.on ('click',监听器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64910052/

相关文章:

javascript - D3圆包图中的图例

javascript - 如何在 SVG 中包含 Bootstrap Glyphicon

javascript - 使用模块模式的变体发出附加 javascript 事件的问题

javascript - 如何将 d3js 中的拖动行为与 Leapjs 结合使用

javascript - D3.js 在指定 nodeSize 时获取树的渲染尺寸

javascript - D3v6 缩放导致指针位置错误

javascript - 从javascript数组计算平均值

javascript - D3.js 和弦图 - 将鼠标悬停在弧上时文本出现/消失

javascript - 丢失事件处理程序并在切换层后重新添加事件处理程序时遇到问题

javascript - d3 六​​边形分箱域和范围