gpt4 book ai didi

JavaScript 范围 : access variable inside event handler?

转载 作者:行者123 更新时间:2023-12-02 18:21:23 25 4
gpt4 key购买 nike

我有以下代码。它在 D3 中绘制一个堆积图,然后允许用户通过从下拉列表中选择一个选项来过滤显示的线条。

但是,我在范围方面遇到了问题。当我使用下拉菜单时,控制台语句显示 series 1 已正确更新。但是 mousemove 代码中的系列 2 尚未更新。

我猜这是因为它是绑定(bind)的并且在变量更新时没有更新。我怎样才能访问更新后的变量?

 d3.csv("/data/test.csv", function(error, data) {

function updateGraph(label) {

// Filter the data.
var series = data.filter(function(d, i) {
return d.Type == label;
});
console.log('series 1', series); // This updates correctly.

// Draw the paths.
var items = svg.selectAll("path").data(newSeries);
items.enter().append('path').attr("d", function(d) {
return area(d.data);
}).on("mousemove", function(d, i) {
console.log('series 2', series); // This is out of date.
});
}

// Draw the initial graph.
updateGraph('initial');
// When the user changes the drop-down, redraw the graph.
d3.select("#chooseoption").on("change", function(val) {
updateGraph(this.options[this.selectedIndex].value);
});

});

最佳答案

如果您希望多个事件处理程序可以访问或修改一个series变量,那么您需要在所有想要参与的事件处理程序之上的范围内定义该变量,以便它们所有共享对同一变量的访问,而不是多个闭包中存在该变量的多个副本。

在这种情况下,你可以这样做:

d3.csv("/data/test.csv", function(error, data) {

// define series variable where multiple event handlers can share it
var series;
function updateGraph(label) {

// Filter the data.
series = data.filter(function(d, i) {
return d.Type == label;
});
console.log('series 1', series); // This updates correctly.

// Draw the paths.
var items = svg.selectAll("path").data(newSeries);
items.enter().append('path').attr("d", function(d) {
return area(d.data);
}).on("mousemove", function(d, i) {
console.log('series 2', series); // This is out of date.
});
}

// Draw the initial graph.
updateGraph('initial');
// When the user changes the drop-down, redraw the graph.
d3.select("#chooseoption").on("change", function(val) {
updateGraph(this.options[this.selectedIndex].value);
});

});

关于JavaScript 范围 : access variable inside event handler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18791728/

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