d3:对一个类采取行动以响应一个事件

d3: acting on a class in response to an event

本文关键字:一个 响应 事件 d3      更新时间:2023-09-26

我正在使用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");
    });

(我预计当点击其中一个节点时,会将所有节点变为红色)不起作用。

通过调用为圆圈设置类名的方式存在错误

.attr("class", ".node")

这样做会将属性设置为class=".node",这肯定不是您想要的。此外,这将不是一个有效的类名。有关允许哪些字符组成类名的解释,请参阅此答案。要选择这个类名,必须执行选择器字符串中有两个点的svg.selectAll("..node")

话虽如此,更改您的代码以去掉圆点使其工作:

.attr("class", "node")

经验教训:

  1. .attr()从字面上获取属性的值。

  2. 当应用CSS选择器时,您可以在它前面加一个点来选择类名。

您需要指定圆的"cx"answers"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");
    });