繁体   English   中英

d3有关从变量创建的表中获取数据的问题(在D3.js v3.5.5中有效,但在v4.2.2中无效)

[英]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)

在Google Chrome版本52.0.2743.116 m(64位)中执行以下D3.js代码(版本4.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> <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> 

这导致:

结果

但我想实现这一目标:

我必须做到这一点

有人知道我的代码有什么问题吗? 我的控制台没有显示任何错误。

编辑:我只是试图在3.5.5中运行它,它的工作。 只是在4.2.2上不起作用

有任何想法吗?

您正在使用D3 v4.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; });

这是关于mergeAPI 您可以在下面的代码中看到它的运行情况:

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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