gpt4 book ai didi

javascript - 如何将 d3 选择保存在数组中供以后使用 D3.js?

转载 作者:行者123 更新时间:2023-12-04 02:01:44 31 4
gpt4 key购买 nike

我试图将选择的圆圈保存在一个数组中,这样我以后就可以操作这些圆圈,而不必搜索页面上的所有圆圈。我希望能够从不同于创建圈子的函数访问圈子。

// From outer function
var selections = [];

// From inner function A
circles.on("click", function(da){
d3.selectAll("circle").filter(function(db){
var result = da.someProperty == db.someProperty;
var circle = d3.select(this);
if(result) selections.push(circle);
return result;
})
.attr("fill", "red");
});

// From inner function B
selections.forEach(function(circle){
circle.attr("fill", "black"); // Doesn't work
});

有没有办法使用我的选择数组的内容修改圆形属性?

最佳答案

从 D3 的 Angular 来看,有一些改进适用于您的方法,这将使您的代码更具可读性和D3ish。尝试按照自己的方式完成 D3 的 concept of selections以更好地理解它。即使不知道您的整个代码,您问题中发布的代码片段也可能会重构为如下所示:

// From outer function
// This will hold the selection in the outer scope.
var selections;

// From inner function A
circles.on("click", function(da){
// Fill in the reference to the selection which is returned by filter().
selections = d3.selectAll("circle").filter(function(db){
return da.someProperty == db.someProperty;
})
.attr("fill", "red");
});

// From inner function B
// No need for an explicit loop here; D3 will take care of that.
selections.attr("fill", "black");

filter() 函数将返回您之后的选择,而无需摆弄任何辅助数组。您只需将对此选择的引用存储在 selections 中,将其保存在外部范围内。

稍后,当您以某种方式想要对这个选择进行操作时,不需要对数组进行显式循环,因为 D3 会处理它。您可以调用它的方法来处理属性、样式、事件处理程序等。参见 API docs d3.select() 上可用的所有方法。

关于javascript - 如何将 d3 选择保存在数组中供以后使用 D3.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172015/

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