我遇到了全局/局部变量问题 在这里,我的代码基于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);
});
这段代码很好用,但我想做的就是能够导出这个代码&#39;在d3.select之外,为了在其他功能中使用它。
下面显示的d3.select已经包含了一些通过Google搜索我的问题找到的建议:
var currentRadius = 0;
d3.select("#nRadius").on("input", function() {
currentRadius = +this.value
console.log("Inside: " + currentRadius);
currentRadius = update(currentRadius);
});
console.log("Outside: " + currentRadius);
但它没有用。
答案 0 :(得分:1)
问题出在这里
//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);
因此,简而言之,全局变量将在更改函数中发生。
在事件被解雇之前,console.log("Outside: " + currentRadius);
已经完成了很多。
我希望这会有所帮助