2014-03-04 47 views
0

我使用下面的代碼爲我的選擇功能如何在d3中動態選擇類?

quadrants = ["a", "b", "c", "d"]; 
for (var i in quadrants) 
{ 
    svgContainer.append("g").attr("class", quadrants[i]); 
    var group = d3.select(function() {return "." + quadrants[i]}); 

    group.append("polygon"); 
    ..... 
} 

這個自組的值不工作是「功能(){回報‘’ +象限[i]'。 我該如何解決這個問題,以便該組選擇「.a」,「.b」等等?

+0

它是一個錯字或你不關閉''{? –

+0

對不起,這是一個錯字。固定。 – user3370384

回答

1

你忘了關{

而且,你並不需要使用的功能,下面的代碼工作:

quadrants = ["a", "b", "c", "d"]; 
for (var i in quadrants) 
{ 
    //svgContainer.append("g").attr("class", quadrants[i]); 
    var group = d3.selectAll('.'+quadrants[i]); 
    group.text(function(){return i}); 
} 

其實用的功能是沒有意義的。該函數的作用是動態地從變量中計算選擇器。但是,使用d3.selectd3.selectAll時,沒有任何內容會傳遞給該功能。

的jsfiddle:http://jsfiddle.net/hTnJq/1/

+0

或'var group = d3.select('。'+ quadrants [i]);' –

+0

非常感謝你...解決了它。你能告訴我爲什麼我不能在select()中使用函數。我是JS和D3的新手,所以這可能是一個noob問題。 – user3370384

+1

'select'也可以工作,但它只會選擇與選擇器對應的所有第一項。這不是你通常想要的課程。例如:http://jsfiddle.net/hTnJq/2/ –

0

它沒有意義的使用功能在d3.selectd3.selectAll語句,因爲你沒有任何要素還作爲函數的di價值的源泉使用。如果選擇語句爲nested selection like selection.selectAll(function),則只能使用該函數,在這種情況下,該函數中將使用父元素的數據和索引值。

但是,還有一個更優雅的方式做你想要做什麼,通過使用D3 data joins

quadrants = ["a", "b", "c", "d"]; 

var group = svgContainer.selectAll("g") //define a selection of <g> elements 
       .data(quadrants); //declare that you want one <g> 
            //for each value in quadrants 

group.enter() //get the placeholder selection for the data objects 
       //that don't have matching elements yet 
    .append('g') //create the elements for each placeholder 
    .attr("class", function(d,i) { 
       //make the class a function of the data 
       //(which is the value from the quadrants array) 
       return d; 
      }); 

group.append("polygon"); //add a polygon to *each* <g> element 
+0

P.S.您可能還會發現[關於匿名函數的更長時間的討論 - 作爲參數](http://stackoverflow.com/questions/21358027/how-are-input-parameters-filled-in-javascript-method-chains/21421101#21421101 )是有用的。 – AmeliaBR