2016-08-18 5 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에서 :

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

는 마우스 오버 것과 "다음"요소를 얻으려면 수행 : 그래서

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(originalSelection.nodes()[i + 1]) 
     .style("fill", someAwesomeColor); 
}); 

originalSelection 인 경우 초기 선택은 .data입니다. 참고, .nodesd3 버전에서만 사용할 수 있습니다 4.

+0

신난다. 나는 실제로 비슷한 것을 시도했다. this.attr (stuff) 그러나 나는 그 주위에 d3.select가 필요하다고 생각한다. 그것은 매력처럼 작동했습니다. – zachvac

+0

언제쯤 우리 수준에 달할 지 궁금합니다 –

+0

실제로 후속 질문이 하나 있습니다. 데이터에서 요소로 가져올 수 있습니까? 예를 들어 각 주마다 색인이 있고, 그것이 끝났을 때 index + 1 (어떤 이유로 든) 상태의 색을 변경하고 싶었지만 어떻게해야합니까? 요소에서 데이터로 이동하는 것이 d3에서 쉬운 것처럼 보이지만 그 반대는 어려워 보입니다. – zachvac