问题
I'm stuck with a global/local variable issue.
Here, my code based on 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 code works just fine, but what I'd like to do is to be able to export 'this.value' outside the d3.select, in order to use it in some other function.
The d3.select showed below already includes some suggestions found by googling my question:
var currentRadius = 0;
d3.select("#nRadius").on("input", function() {
currentRadius = +this.value
console.log("Inside: " + currentRadius);
currentRadius = update(currentRadius);
});
console.log("Outside: " + currentRadius);
But it doesn't work.
回答1:
The problem is here
//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);
So in short the global variable change will happen in the change function.
And the console.log("Outside: " + currentRadius);
is done much before that event got fired.
I hope this helps
来源:https://stackoverflow.com/questions/34199485/d3-js-how-to-update-a-global-variable-from-d3-select