我对变量范围有疑问。在下面的代码中,我有两个变量,我想为它们分配一些值,然后在代码中使用这些值。 变量是:eSVG,originMouse。 我在使用mousedown事件函数时分配它们的值,然后尝试在mousemove事件函数中使用这些值,但我总是得到未定义的值。 你能告诉我这里发生了什么吗?
谢谢你们
var eSVG, originMouse;
svg.on("mousedown", function() {
eSVG= this, // svg element
originMouse = d3.mouse(eSVG), // mouse origing
rect = svg.append("rect").attr("class", "zoom");
originMouse[0] = Math.max(0, Math.min(width, originMouse[0]));
originMouse[1] = Math.max(0, Math.min(height, originMouse[1]));
})
.on("mousemove", function() {
console.log(eSVG); **// undefined**
var m = d3.mouse(eSVG);
console.log(originMouse); **// undefined**
m[0] = Math.max(0, Math.min(width, m[0]));
m[1] = Math.max(0, Math.min(height, m[1]));
rect.attr("x", Math.min(originMouse[0], m[0])-130)
.attr("y", Math.min(originMouse[1], m[1])-80)
.attr("width", Math.abs(m[0] - originMouse[0]))
.attr("height", Math.abs(m[1] - originMouse[1]));
})
答案 0 :(得分:1)
这是我在考虑Dogbert评论后所做的事情:
var eSVG, originMouse;
svg.on("mousedown", function() {
eSVG= this, // svg element
originMouse = d3.mouse(eSVG), // mouse origing
rect = svg.append("rect").attr("class", "zoom");
originMouse[0] = Math.max(0, Math.min(width, originMouse[0]));
originMouse[1] = Math.max(0, Math.min(height, originMouse[1]));
svg.on("mousemove", function() {
console.log(eSVG); **// defined **
var m = d3.mouse(eSVG);
console.log(originMouse); **// defined **
m[0] = Math.max(0, Math.min(width, m[0]));
m[1] = Math.max(0, Math.min(height, m[1]));
rect.attr("x", Math.min(originMouse[0], m[0])-130)
.attr("y", Math.min(originMouse[1], m[1])-80)
.attr("width", Math.abs(m[0] - originMouse[0]))
.attr("height", Math.abs(m[1] - originMouse[1]));
})
d3.event.stopPropagation();
})