D3根据数据改变链接的颜色

时间:2016-12-14 22:52:44

标签: javascript d3.js

我是javascript和d3的新手,我一直在使用一些共享代码,我一直在尝试修改它。

以下是我目前的情况:

https://gist.github.com/erich-kuehn/2770a7c7c1cd633f6b47ebb21b640f68

它基于:

http://bl.ocks.org/erikhazzard/6201948

我正在尝试根据我添加了名为status的csv的新字段来更改链接的颜色。它似乎运行正常,如果我单步执行代码它似乎使一些链接红色和一些绿色,但当它完成时,它们都结束绿色。思考?对不起,我真的很陌生。

 //update
    for(var i=0, len=links.length; i<len; i++){
    if (links[i].status[0][0] === 'red') {
    pathArcs.attr({
            //d is the points attribute for this path, we'll draw
            //  an arc between the points using the arc function
            d: path
        })
        .style({
            stroke: 'red',
            'stroke-width': '2px'
        })
        // Uncomment this line to remove the transition
        .call(lineTransition); 

    //exit
    pathArcs.exit().remove();
        }else{
   pathArcs.attr({
            //d is the points attribute for this path, we'll draw
            //  an arc between the points using the arc function
            d: path
        })
        .style({
            stroke: 'green',
            'stroke-width': '2px'
        })
        // Uncomment this line to remove the transition
        .call(lineTransition);

    //exit
    pathArcs.exit().remove();
}   
    }
});

1 个答案:

答案 0 :(得分:0)

pathArcs是一系列元素,数据绑定到它们。当您调用选择方法(attrstyletext等)时,它将迭代选择中的所有元素。如果提供静态值,则会为每个元素赋予该值。如果你提供一个函数,那么每个元素都会调用该函数传递两个参数,第一个是绑定到元素的数据,第二个是元素的选择索引。此函数的返回值是您要为attrstyletext等分配的值。

在代码中,无论何时进行这些pathArcs方法调用,都要为选择中的每个元素设置值。你最终得到了所有的绿色元素,因为for循环中的最后一个元素使它们全部变为绿色。

您可能已经注意到,if / else语句的唯一区别在于您设置stroke颜色的位置。这意味着您只需要为样式的stroke值提供函数。

pathArcs
  .attr({
    d: path
  })
  .style({
    'stroke': function(d) {
      // I don't know if you can just set this based on the
      // value of d.status[0][0] without knowing the possible
      // values of it. Ternary may be unnecessary.
      return d.status[0][0] === 'red' ? 'red' : 'green';
    }),
    'stroke-width': '2px'
  })
  // Uncomment this line to remove the transition
  .call(lineTransition); 
相关问题