gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:53:03 26 4
gpt4 key购买 nike

在以前的版本中,可以通过以下方式检索索引 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com