2015-01-09 4 views
0

D3을 사용하여 색으로 구분 된지도를 작성했으며 사용자가 연도 버튼을 클릭하여 연도별로 데이터를 볼 수있게하려는 다음 단계를 수행하려고합니다. 각 버튼에 onclick 함수를 첨부하고이 함수는 my displayYear 변수를 업데이트합니다. 나는이 변수가 올바르게 업데이트되고 있는지 확인하기 위해 console.log에 던져 넣었다. 그러나 어떤 이유로 내지도가 업데이트되지 않고 무엇을 클릭했는지에 관계없이 초기 값으로 유지됩니다. 내 HTML 및 자바 스크립트/D3 코드는 다음과 같습니다 :D3 데이터가 onclick 함수를 통해 업데이트되지 않음

관련 HTML :

<button onclick="setYear(0)">2009</button> 
<button onclick="setYear(1)">2010</button> 
<button onclick="setYear(2)">2011</button> 
<button onclick="setYear(3)">2012</button> 
<button onclick="setYear(4)">2013</button> 
<button onclick="setYear(5)">2014</button> 

관련 JS :

//Bind premium and map data and create one path per mapData feature 

var displayYear = 0; 
function setYear(index) { 
    displayYear = index; 
    console.log(displayYear); 
}   

premSvg.selectAll("path") 
     .data(mapData.features) 
     .enter() 
     .append("path") 
     .attr("d", path) 
     .style("fill", function(d) { 
      //Get data value 
      var value = d.properties.premium[displayYear].value; 

      if (value) { 
        //If value exists… 
        return premColor(value); 
      } else { 
        //If value is undefined… 
        return "#ccc"; 
      } 
     }) 
     .style("stroke","grey") 
     .append("title") 
     .text(function(d) { 
       return d.properties.name + ": $" + d3.format(",")(Math.round(d.properties.premium[displayYear].value)); 
     }); 

답변

1

내 setYear 기능을 작성 내 "경로"를 업데이트하는 코드를 포장 결국 :

function setYear(index) { 
    displayYear = index; 

    premSvg.selectAll("path") 
      .style("fill", function(d) { 
       //Get data value 
       var value = d.properties.premium[displayYear].value; 

       if (value) { 
        //If value exists… 
        return premColor(value); 
       } else { 
        //If value is undefined… 
        return "#ccc"; 
       } 
      }) 
      .style("stroke","grey") 
      .append("title") 
      .text(function(d) { 
       return d.properties.name + ": $" + d3.format(",")(Math.round(d.properties.premium[displayYear].value)); 
      }); 
} 

function setYear(index) { 
       displayYear = index; 

       premSvg.selectAll("path") 
         .style("fill", function(d) { 
          //Get data value 
         var value = d.properties.premium[displayYear].value; 

         if (value) { 
          //If value exists… 
          return premColor(value); 
         } else { 
          //If value is undefined… 
          return "#ccc"; 
         } 
        }) 
        .style("stroke","grey"); 

       premSvg.selectAll("title") 
         .text(function(d) { 
         return d.properties.name + ": $" + d3.format(",")(Math.round(d.properties.premium[displayYear].value)); 
       }); 
      } 
관련 문제