简体   繁体   中英

d3 issue with getting data out of a table created from a variable (works in D3.js v3.5.5 but not in v4.2.2)

After executing the following D3.js code (version 4.2.2) in Google Chrome version 52.0.2743.116 m (64-bit):

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);

I am getting the following HTML code in the console (elements section):

 <html> <head> <meta charset="UTF-8"> <title>D3 Data binding</title> <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> 

Which leads to this:

结果

But I want to achieve this:

我必须做到这一点

Anyone knows what can be wrong with my code? My console shows me no errors at all.

Edit: I just tried to run it in 3.5.5 and it worked. It just doesn't work on 4.2.2

Any ideas?

You are using D3 v 4.x. In this case, you have to merge the selections:

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

This is the API regarding merge . You can see it working in the code below:

 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 dx; }) .attr("cy", function(d){ return dy; }); } 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM