2015-01-09 21 views
0

我已經使用D3構建了一個顏色編碼的地圖,並希望採取下一步允許用戶按年按鈕查看數據。我爲每個按鈕附加了一個onclick函數,該函數更新了我的displayYear變量。我扔了一個console.log,以確保這個變量正在更新正確,它是。但是,由於某種原因,我的地圖從不更新,無論點擊什麼,它都保持其初始值。我的HTML和Javascript/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)); 
       }); 
      }