点击d3 javascript替代颜色

rep*_*cus 12 javascript d3.js

我刚刚开始玩d3,并且想知道如何在点击它时交替元素的颜色.

这个小提琴改变了点击它的圆圈的颜色,但是我想再次点击后将颜色恢复为白色.

现行代码:

var sampleSVG = d3.select("#viz")
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);    

    sampleSVG.append("circle")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("r", 40)
        .attr("cx", 50)
        .attr("cy", 50)
        .on("click", function(){d3.select(this).style("fill", "magenta");});
Run Code Online (Sandbox Code Playgroud)

Nea*_*eal 19

让自己成为一个切换功能并将其传递给点击:http://jsfiddle.net/maniator/Bvmgm/6/

var toggleColor = (function(){
   var currentColor = "white";

    return function(){
        currentColor = currentColor == "white" ? "magenta" : "white";
        d3.select(this).style("fill", currentColor);
    }
})();
Run Code Online (Sandbox Code Playgroud)