简体   繁体   English

d3 javascript click函数调用

[英]d3 javascript click function call

I'm trying to get d3 to change the color of plot points upon clicking them, but can't seem to get this working at the moment. 我正在尝试让d3在单击它们时更改打印点的颜色,但目前似乎无法正常工作。 The commented line below does change the color from white to magenta, but the toggleColor function does not seem to do anything. 下面的注释行的确将颜色从白色更改为洋红色,但是toggleColor函数似乎没有任何作用。 Actually, the alert only happens when first run, and not when a point is clicked. 实际上,警报仅在首次运行时发生,而不是在单击某个点时发生。 What am I doing wrong here? 我在这里做错了什么?

var circle = graph.selectAll("circle.value")
    .data(data)
    .enter().append("circle")
    .attr("class", "value")
    .attr("cx", function(d) { return x(d.hour); })
    .attr("cy", function(d) { return y(d.value); })
    .attr("r", 5)
    //.on("click", function(){d3.select(this).attr("class", "flagged");});
    .on("click", toggleColor);


var toggleColor = (function(){
    // throw in an alert for good measure. . .
    alert("Clicked?")
    var currentColor = "white";
    return function(){

        currentColor = currentColor == "white" ? "magenta" : "white";
        d3.select(this).atrr("class", "flagged");
    }
   })();

To begin with, var toggleColor is still undefined at the point where you're wiring up the click event (because it's defined further down the page). 首先,在连接click事件时,仍未定义var toggleColor (因为它是在页面下方定义的)。 So you need to move it up. 因此,您需要将其向上移动。

Then, the reason the alert appears only once, at runtime, is because that's when that code is run. 然后,警报在运行时仅出现一次的原因是因为那是该代码运行的时间。 If you notice, the outer function is executed right after it's declared, as evident by the () at the very last line of the code. 如果您注意到,外部函数在声明之后立即执行,如代码最后一行的() That's when alert() gets called. 那是当alert()被调用时。 You'll want to move it into the body of the inner function -- the one that's returned -- because that inner function is the code that will actually run on click. 您需要将其移动到内部函数的主体(返回的主体)中,因为该内部函数是在单击时实际运行的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM