2016-08-18 12 views
1

私はD3を学んでいますが、これまでは米国の地図を表示する基本的なアプリを持っていて、ユーザーがテキストを追加する状態にマウスを置くと、私がやりたいことは、マウスを重ねると状態が違う色に変わることです。私がこれまで持っているもの:私はdでデータを参照することができますがD3 - データで要素を識別する

var svg = d3.select("body") 
    .append("svg") 
    .attr("width", 500) 
    .attr("height", 500); 

d3.json("/HelloWorld/data/states.json", function(data) { 
    var projection = d3.geo.albersUsa().translate([250,250]).scale(650); 
    var path = d3.geo.path().projection(projection); 
    svg.selectAll("path") 
    .data(data.features) 
    .enter() 
    .append("path") 
     .attr("d",path) 
     .attr("fill", "red") 
     .attr("stroke", "blue") 
     .on("mouseover", function(d, i) { 

    d3.select("body").append("text").html("</br>"+d.properties.NAME); 
}); 

は問題がある、私は塗りつぶし属性を変更するためにパスオブジェクトを参照できるようにする必要があり、私はしませんよデータから実際のSVG要素に到達する方法を確認してください。

+0

チェックこれ:http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922 –

+0

'this'キーワードがマウスオーバーされているデータ要素を指します。 – Mark

答えて

0

thisキーワードは、マウスオーバーするデータ要素を指します。 docsから:

When a specified event is dispatched on a selected node, the specified listener will be evaluated for each selected element, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element. Listeners always see the latest datum for their element, but the index is a property of the selection and is fixed when the listener is assigned; to update the index, re-assign the listener. To access the current event within a listener, use d3.event.

それでは、実行します。

.on("mouseover",function(d,i){ 
    d3.select("body") 
     .append("text") 
     .html("</br>"+d.properties.NAME); 
    d3.select(this) 
     .style("fill", someAwesomeColor); 
}); 

をあなたがマウスオーバー1から "次" の要素を取得するには:originalSelectionがある

.on("mouseover",function(d,i){ 
    d3.select(originalSelection.nodes()[i + 1]) 
     .style("fill", someAwesomeColor); 
}); 

最初の選択は.dataとなります。 .nodesd3バージョンでのみ利用可能である。4.

+0

素晴らしいですが、私は実際に何かを試してみました this.attr(stuff) 私はそれの周りにd3.selectが必要だったと思います。それは魅力のように働いた。 – zachvac

+0

いつ私がレベルに達するのだろうか –

+0

実際に私にはフォローアップの質問が1つありますが。データから要素に到達することは可能ですか?たとえば、各州にはインデックスがあり、それがマウスオーバーしたとき、私はindex + 1(何らかの理由で)の状態の色を変更したいのですが、どうすればいいですか?要素からデータへの到達はd3では簡単ですが、その逆は難しいようです。 – zachvac

関連する問題