1

我对变量范围有疑问。在下面的代码中,我有两个变量,我想为它们分配一些值,然后在代码中使用这些值。变量是: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]));
  })
4

1 回答 1

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();
})
于 2013-06-12T12:51:54.610 回答