2016-12-14 10 views
0

私はjavascriptとd3の新機能ですが、私はいくつかの共有コードを使って作業しており、変更しようとしています。ここでD3データに基づくリンクの色を変更しました

は、私が現在持っているものです。

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

のオフに基づいて

その:

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

を私は新しいフィールドに基づいて、リンクの色を変更しようとしていますステータスと呼ばれるcsvを追加しました。それはOKを介して実行するようだと私はコードをステップインすると、いくつかのリンクを赤といくつかの緑を作るようだが、完了したとき、彼らはすべて緑色に終わる。思考?申し訳ありません、私はこれで本当に新しいです。

//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(); 
} 
    } 
}); 

答えて

0

pathArcsは、データがバインドされた要素の選択です。選択範囲のメソッド(attrstyletextなど)を呼び出すと、選択範囲内のすべての要素を繰り返し処理します。静的な値を指定すると、各要素にその値が与えられます。関数を提供すると、各要素はその関数を2つの引数を渡して呼び出します。最初の要素は要素にバインドされたデータで、2番目の要素は選択範囲内の要素のインデックスです。この関数の戻り値は、あなたがこれらのpathArcsメソッド呼び出しを作っている時はいつでも、あなたは選択のすべての要素の値を設定するなど、あなたのコードで

attrstyletextのために割り当てたいものです。 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); 
関連する問題