gpt4 book ai didi

javascript - D3.js 如何从 d3.select() 更新全局变量

转载 作者:行者123 更新时间:2023-12-03 08:09:43 25 4
gpt4 key购买 nike

我遇到了全局/局部变量问题。
在这里,我的代码基于 http://www.d3noob.org/2014/04/using-html-inputs-with-d3js.html

index.html

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Input test (circle)</title>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<p>
<label for="nRadius"
style="display: inline-block; width: 240px; text-align: right">
radius = <span id="nRadius-value">…</span>
</label>
<input type="range" min="1" max="150" id="nRadius">
</p>
<script src="./slider.js"></script>
</body>
</html>

slider .js

// update the circle radius
function update(nRadius) {
// adjust the text on the range slider
d3.select("#nRadius-value").text(nRadius);
d3.select("#nRadius").property("value", nRadius);

// update the circle radius
circle.selectAll("circle").attr("r", nRadius);
return nRadius;
}

var width = 600;
var height = 300;
var circle = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);

// Circle with no radius
circle.append("circle")
.attr("cx", 300)
.attr("cy", 150)
.style("fill", "none")
.style("stroke", "blue");

// Initial radius
update(50);

// when the input range changes update the circle
d3.select("#nRadius").on("input", function() {
update(+this.value);
});

这段代码工作得很好,但我想做的是能够将“this.value”导出到 d3.select 之外,以便在其他函数中使用它。

下面显示的 d3.select 已经包含通过谷歌搜索我的问题找到的一些建议:

var currentRadius = 0;
d3.select("#nRadius").on("input", function() {
currentRadius = +this.value
console.log("Inside: " + currentRadius);
currentRadius = update(currentRadius);
});

console.log("Outside: " + currentRadius);

但是这不起作用。

最佳答案

问题就在这里

//this is your global variable
var currentRadius = 0;

d3.select("#nRadius").on("input", function() {
//you are changing the global value here on change event.
currentRadius = +this.value
console.log("Inside: " + currentRadius);
currentRadius = update(currentRadius);
//call your function
outside();
});
//some function somewhere
function outside(){
console.log(currentRadius)
}
//value of global variable when this executed is 0
//because no change event has been called
console.log("Outside: " + currentRadius);

所以简而言之,全局变量的改变会在change函数中发生。console.log("Outside: "+ currentRadius); 是在该事件触发之前完成的。

希望这有帮助

关于javascript - D3.js 如何从 d3.select() 更新全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199485/

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