JavaScript作用域:访问事件处理程序中的变量?
我有以下代码。它在D3中绘制一个堆叠图形,然后允许用户通过从下拉列表中选择一个选项来过滤显示的线条 然而,我对范围有问题。当我使用下拉列表时,console语句显示JavaScript作用域:访问事件处理程序中的变量?,javascript,Javascript,我有以下代码。它在D3中绘制一个堆叠图形,然后允许用户通过从下拉列表中选择一个选项来过滤显示的线条 然而,我对范围有问题。当我使用下拉列表时,console语句显示series 1已正确更新。但是,mousemove代码中的系列2没有更新 我猜这是因为它是绑定的,并且在变量更新时没有更新。如何访问更新的变量 d3.csv("/data/test.csv", function(error, data) { function updateGraph(label) { // Filt
series 1
已正确更新。但是,mousemove代码中的系列2没有更新
我猜这是因为它是绑定的,并且在变量更新时没有更新。如何访问更新的变量
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);
});
});
如果希望有一个
系列
变量供多个事件处理程序访问或修改,则需要在所有要参与的事件处理程序之上的作用域中定义该变量,以便它们共享对同一变量的访问权限,而不是在多个闭包中存在该变量的多个副本
在这种情况下,您可以这样做:
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);
});
});