我正在研究一个简单的 d3 示例,我使用 d3 在页面上放置一些新的 div、添加属性和添加数据驱动的样式。让我绊倒的部分是当我想使用 d3 使用新数据更新某些样式时。我从下面的 jsFiddle ( http://jsfiddle.net/MzPUg/15/ ) 中粘贴了代码。
在最初创建 div 的步骤中,我使用键函数向元素添加索引,在更新步骤(不起作用的部分)中,我还使用键函数。但是从 d3 文档中不清楚的是实际数据连接是如何工作的(例如,索引存储在 DOM 元素中的什么位置?如果有重复的索引怎么办?等等)。
所以,我的知识存在明显的差距,但是在这里保持简单,任何人都可以解释为什么这个例子不起作用?任何有关 d3 中数据连接的精确性质的额外信息都将是锦上添花。(我已经看过http://bost.ocks.org/mike/join/。)
//add a container div to the body and add a class
var thediv = d3.select("body").append("div").attr("class","bluediv");
//add six medium-sized divs to the container div
//note that a key index function is provided to the data method here
//where do the resulting index value get stored?
var mediumdivs = thediv.selectAll("div")
.data([10,50,90,130,170,210],function(d){return d})
.enter().append("div")
.style("top",function(d){return d + "px"})
.style("left",function(d){return d + "px"})
.attr("class","meddiv")
//UPDATE STEP - NOT WORKING
//Attempt to update the position of two divs
var newdata = [{newval:30,oldval:10},{newval:80,oldval:50}]
var mediumUpdate = mediumdivs.data(newdata,function(d){return d.oldval})
.style("left",function(d){return d.newval + "px"})