2012-08-10 5 views
13

d3 시각화에 드롭 다운 메뉴를 추가하려고합니다. 문제는 eventlistener가 옵션을 선택할 때 호출되지 않는다는 것입니다. 또한 선택한 옵션 값에 어떻게 액세스 할 수 있습니까? 다음은 당신은 select 요소가 아닌 option 요소에 .on("change")를 추가 할 필요가 ... Thankxd3.js를 사용하여 드롭 다운 메뉴 추가

답변

32

d3.text("uniqueTeams.php",function(json){ 
    var dd=JSON.parse(json); 
    var b= d3.select("#s4").select("#shru"); 
    var u=b.append("select"); 
    var t=u.selectAll("option").data(dd).enter().append("option") 
     .attr("value",function(d){return d.teamShotID;}) 
     .text(function(d){return d3.select(this).node().__data__.teamShotID;}); 
    t.on("change",change); 
}); 
function change(value) 
{ 
    console.log("team",value); 
} 
change();​​​​ 

내 코드의 조각이다.

var select = d3.select("#shru").append("select").on("change", change), 
    options = select.selectAll('option').data(dd); // Data join 

// Enter selection 
options.enter().append("option").text(function(d) { return d.teamShotID; }); 

현재 선택된 option 인덱스

select selectedIndex 요소라는 속성을 유지한다. Selections are arrays, so elements can be accessed directly (e.g., selection[0][0]). 나는 또한이 대안 구문을 포함하려면, 가독성과 희망 당신은 위의 코드를 이해하는 데 도움이 :

function change() { 
    var selectedIndex = select.property('selectedIndex'), 
     data   = options[0][selectedIndex].__data__; 
} 

편집 : 각 option 요소는 데이터 __data__라는 속성에 저장, 바인드 것이다

이 당신을 안내 할 수
function change() { 
    var si = select.property('selectedIndex'), 
     s = options.filter(function (d, i) { return i === si }), 
     data = s.datum(); 
} 
0

희망 ...

 var dispatch = d3.dispatch("load", "countrychange"); 
    d3.csv("data/ERSreputationBlocked.csv",type, function (error, country) { 
     if (error) throw error; 
     var countryById = d3.map(); 
     country.forEach(function (d) { countryById.set(d.id, d); }); 
     dispatch.load(countryById); 
     dispatch.countrychange(countryById.get("PH")); 
     //console.log(country); 
    }); 
    dispatch.on("load.menu", function(countryById) { 
     var select = d3.select("body") 
     .append("div") 
     .append("select") 
     .on("change", function() { dispatch.countrychange(countryById.get(this.value)); }); 

     select.selectAll("option") 
     .data(countryById.values()) 
     .enter().append("option") 
     .attr("value", function (d) { return d.id; }) 
     .text(function (d) { return d.Country; }); 

     dispatch.on("countrychange.menu", function (country) { 
      select.property("value", country) 
      //loading the value based on the selected data 
      var svg1 = d3.select("body").append("svg1") 
       .attr("width", width) 
       .attr("height", height) 
      //end of selection 

     console.log(country); 
     }); 
    }); 
    //end of drop down 

    function type(d) { 
     d.total = d3.sum(d.value, function (k) { return d[k] = +d[k]; }); 
     return d; 
    }