2013-02-21 50 views
0

我無法處理在我的D3代碼的事件處理程序:重構之前,正在按原計劃:不斷指標傳遞給d3.js事件處理

choice_groups 
    .append("span") 
    .attr("class", "repeat-choice") 
    .text("Modifica questa scelta") 
    .on("click", repeat_choice); 

的repeat_choice()函數調用點擊span.repeat-choice元素的索引i參數。

由於我只要附加這個事件處理程序,其具有一個以上的嵌套的數據元件的元件,我重構上述這樣的代碼:

choice_groups 
    .each(function(d, i) { 
    if(d.length > 1) { 
     d3.select(this) 
     .append("span") 
     .attr("class", "repeat-choice") 
     .text("Modifica questa scelta") 
     .on("click", repeat_choice); 
    } else { 
     d3.select(this) 
     .append("span") 
     .attr("class", "no-choice") 
     .html(" "); 
    } 
    }); 

然而,repeat_choice()處理功能現在總是得到用i = 0調用,無論哪個元素是被點擊的索引。

我想我沒有正確使用selection.each():結果標記符合預期(和重構之前一樣),只有click處理函數不會傳遞元素的索引。

回答

2

您的內部d3.select()正在創建一個新選擇,因此每次都重置i = 0(在該選擇的上下文中)。您可以有條件地設置屬性:

choice_groups 
    .append("span") 
    .attr("class", function(d,i) { return d.length > 1 ? "repeat-choice" : "no-choice"; }) 
    .text(function(d,i) { return d.length > 1 ? "Modifica questa scelta" : null; }); 

或可能重新選擇只有「重複選擇」的元素,並綁定點擊後處理:

choice_groups 
    .filter(function(d,i){ return d.length > 1;}) 
    .on("click", repeat_choice); 

(傳遞給repeat_choice的,我將只計算過濾我認爲)在這第二個選擇元素

希望幫助。