2016-08-26 31 views
0

在Google Chrome版本中執行以下D3.js代碼(版本4.2.2)後52.0.2743.116米(64位):d3與從變量創建的表中獲取數據的問題(適用於D3.js v3.5.5,但不適用於v4.2.2)

var svg = d3.select("body").append("svg") 
      .attr("width", 250) 
      .attr("height", 250); 

function render(data) 
{ 
    //Bind Data 
    var circles = svg.selectAll("circle").data(data); 

    //Enter 
    circles.enter().append("circle") 
    .attr("r", 10); 

    //Update 
    circles 
    .attr("cx", function(d){ return d.x; }) 
    .attr("cy", function(d){ return d.y; }); 

    //Exit 
    circles.exit().remove(); 
} 

var myArrayOfObjects = 
[ 
    { x: 100, y: 100}, 
    { x: 130, y: 120}, 
    { x: 60, y: 80}, 
    { x: 70, y: 110}, 
    { x: 90, y: 30}, 
    { x: 20, y: 10} 
]; 

render(myArrayOfObjects); 

我正在在控制檯(元件部)下面的HTML代碼:

<html> 
 
    <head> 
 
\t <meta charset="UTF-8"> 
 
\t <title>D3 Data binding</title> 
 
\t <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> 
 
</head> 
 
<script>...</script> 
 
    <svg width="250" height="250"> 
 
    <circle r="10"></circle> 
 
    <circle r="10"></circle> 
 
    <circle r="10"></circle> 
 
    <circle r="10"></circle> 
 
    <circle r="10"></circle> 
 
    <circle r="10"></circle> 
 
    </svg> 
 
</html>

哪導致這個:

The result

但我想做到這一點:

I have to achieve this

任何人都知道什麼都可以錯我的代碼?我的控制檯根本不顯示任何錯誤。

編輯:我只是試圖運行它在3.5.5,它的工作。它只是不適用於4.2.2

任何想法?

+1

我http://jsfiddle.net/a08n4986/看起來不錯。您是否嘗試清除瀏覽器緩存? –

+0

我做過了,但沒有解決問題。 – ay43210

+0

我認爲它與d3.js – ay43210

回答

0

您正在使用D3 v 4.x.在這種情況下,你必須merge的選擇:

circles.enter().append("circle") 
    .attr("r", 10).merge(circles) 
    .attr("cx", function(d){ return d.x; }) 
    .attr("cy", function(d){ return d.y; }); 

這是API regarding merge。你可以看到它在下面的代碼工作:

var svg = d3.select("body").append("svg") 
 
      .attr("width", 250) 
 
      .attr("height", 250); 
 

 
function render(data) 
 
{ 
 
    //Bind Data 
 
    var circles = svg.selectAll("circle").data(data); 
 
    
 
    //Exit 
 
    circles.exit().remove(); 
 

 
    //Enter and Update 
 
    circles.enter().append("circle") 
 
    .attr("r", 10).merge(circles) 
 
    .attr("cx", function(d){ return d.x; }) 
 
    .attr("cy", function(d){ return d.y; }); 
 

 

 
} 
 

 
var myArrayOfObjects = 
 
[ 
 
    { x: 100, y: 100}, 
 
    { x: 130, y: 120}, 
 
    { x: 60, y: 80}, 
 
    { x: 70, y: 110}, 
 
    { x: 90, y: 30}, 
 
    { x: 20, y: 10} 
 
]; 
 

 
render(myArrayOfObjects);
<script src="https://d3js.org/d3.v4.min.js"></script>

+1

謝謝,現在它終於起作用了。 – ay43210

相關問題