2015-02-10 81 views
2

我有一個陣列var brands = ['Option1', 'Option2']。我想用D3輸出標記單選按鈕,如下所示:D3:如何創建輸入元素後跟標籤文本?

<label> 
    <input type="radio" name="brand" value="Option1" checked="true"/> Option1 
</label> 
<label> 
    <input type="radio" name="brand" value="Option2" /> Option2 
</label> 

這是我的D3,但它並不完全工作:

var radios = d3.select('.panel.left').selectAll('input[name="brand"]').data(brands); 
var labels = radios.enter() 
     .append("label") 
     .attr("for", function(d) { return d; }) 
     .text(function(d) { return d; }) 
     .append("input") 
     .attr("type", "radio") 
     .attr("name", "brand") 
     .attr("value", function(d) { return d; }) 
     .attr('checked', function(d) { if (d === brands[0]) { return 'checked' }; }); 
d3.selectAll('input[name="brand"]').on('change', function() { 
    renderValues(this.value); 
}); 

這是非常接近的工作,但它輸出這樣的:

<label> 
    Option1 <input type="radio" name="brand" value="Option1" checked="true" /> 
</label> 
<label> 
    Option2 <input type="radio" name="brand" value="Option2" /> 
</label> 

無論我做什麼,我都無法弄清楚如何將文字放在<input>元素之後。我應該做什麼不同?

如果我不必在最後重新選擇要添加偵聽器的輸入元素,那也不錯。

+0

你見過[本教程(http://www.d3noob.org/2014/04/using-html-inputs-with-d3js:在.append( 「輸入」)添加偵聽器後html的)? – 2015-02-10 14:28:20

+0

謝謝,但除非我錯過了某些東西,否則該教程中所有輸入和標籤元素的排序已經硬編碼到HTML中。我有興趣爲動態列表生成它們。 – Richard 2015-02-10 14:39:37

回答

0

嘗試在腳本的末尾添加這樣的:

d3.selectAll("label") 
    .data(brands) 
    .append("text") 
    .text(function(d) { return d; }); 

,並刪除這些行:

.attr("for", function(d) { return d; }) 
.text(function(d) { return d; }) 

你並不需要重新選擇輸入。

.append("input") 
.on('change', function() { 
    renderValues(this.value); 
}) 
+0

謝謝,這有效。我不需要重新綁定數據,我只是做了''d3.selectAll(「label」)。append(「text」).text(function(d){return d;});'。聰明地使用SVG文本元素。 – Richard 2015-02-10 14:56:13