d3:响应某个事件而在课堂上表演

时间:2015-10-29 16:18:47

标签: javascript d3.js

我使用d3将数据绑定到一堆节点,我想安排它,以便在点击其中一个节点(或其他一些事件)时动态更改所有节点。根据我对d3的理解,我认为它应该是这样的:

var nodes = svg.selectAll(".node")
    .data(someData)
    .enter()
    .append("circle") 
    .attr("r", 5)
    .attr("class", ".node")
    .style("fill", "blue")
    .on("click", function(d, i) {
        svg.selectAll(".node").style("fill", function(e, j) {
            if(someCondition(i, j))
                return "red";
            else
                return "green";
        });
    });

但点击时没有任何反应。即使是更简单的代码:

var nodes = svg.selectAll(".node")
    .data(someData)
    .enter()
    .append("circle") 
    .attr("r", 5)
    .attr("class", ".node")
    .style("fill", "blue")
    .on("click", function(d, i) {
        svg.selectAll(".node").style("fill", "red");
    });

(我希望在点击其中一个节点时将所有节点变为红色)不起作用。

2 个答案:

答案 0 :(得分:3)

通过调用

为您的圈子设置班级名称的方式有误
.attr("class", ".node")

这样做会将属性设置为class=".node",这肯定不是你想要的。而且,这不是有效的类名。有关允许哪些字符形成类名的说明,请参阅此answer。要选择此类名称, 必须在选择器字符串中执行svg.selectAll("..node")两个点。

话虽如此,更改代码以省略点以使其工作:

.attr("class", "node")

经验教训:

  1. .attr()从字面上理解属性的值。

  2. 应用CSS选择器时,在其前面加一个点以选择类名。

答案 1 :(得分:-1)

您需要指定圆圈的“cx”和“cy”属性,否则您将看不到任何内容。

var nodes = svg.selectAll(".node")
    .data(someData)
    .enter()
    .append("circle") 
    .attr("r", 5)
    //add cx and cy here: 
    .attr("cx", function(d) {return d+10;/*just an example*/})
    .attr("cy", function(d) {return 2*d+10;/*just an example*/})
    .attr("class", "node")
    .style("fill", "blue")
    .on("click", function(d, i) {
        svg.selectAll(".node").style("fill", "red");
    });