2013-03-15 34 views
0

有人知道爲什麼我在輸入或更新數組值時在我的d3刻度中完全排列了佈局介於5和9之間且大於100在d3.js中顯示列表的奇怪行爲

我已經設置好的了這裏的例子:http://bl.ocks.org/vertighel/5149663

barchart

正如你可以從代碼,並在此圖片中看到,條形圖不得超過500像素的寬度和橙色的顏色。 .. 但嘗試插入5和9之間的值或大於100,你會看到。讓我們改變了 「11」 「9」:

screwed up

寬度和顏色完全規模搞砸了!

這是代碼:

<!doctype html> 
<meta charset="utf8"></meta> 
<title>Test</title> 
<style type="text/css"> 
    li{border: 1px solid white; background-color: steelblue; color: white} 
    li{width: 50px; text-align:right; } 
    li:hover{opacity:0.7;} 
    .clicked{background-color: green} 
    :invalid{background-color: pink} 
</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<input id="inp" value="1,23,42,20,11,33,21" pattern="(\d+)(,\s*\d+)*" required> 
<label for="inp">change me</label> 
<h1>click on the bars</h1> 

<script> 

var list = d3.select("body").append("ul"); 

update() 
d3.select("input").on("change",update) 

function update(){ 
var array = d3.select("input").property("value").split(",") 
console.log(array); 

var cscale = d3.scale.linear() 
.domain(d3.extent(array)) 
.range(["steelblue","orange"]) 

var wscale = d3.scale.linear() 
.domain(d3.extent(array)) 
.range(["10px","500px"]) 

var elem = list.selectAll("li").data(array); 

elem.enter() 
.append("li") 

elem.text(function(d){return d}) 
.transition() 
.style("width", function(d){return wscale(d)}) 
.style("background-color", function(d){return cscale(d)}) 

elem.on("click",function(d,i){d3.select("h1").text("list item "+i+" has value "+d)}) 

elem.exit().remove() 

} 

</script> 

回答

2

你看到這一點,因爲你的數字是不實際的數字,但字符串。特別是,「9」只有一個字符長,而所有其他「數字」是兩個字符長(類似於「100」)。

解決方案是將您的字符串轉換爲整數。這樣做的一種方法是使用map()函數,如下所示。更換

var array = d3.select("input").property("value").split(",") 

var array = d3.select("input").property("value").split(",") 
       .map(function(d) { return(+d); }); 

map()功能可能會或可能不會在您的設置來實現,見here瞭解更多信息,你可以使用一個實現。

+0

謝謝,這解決了我的問題! – 2013-03-15 17:28:17