javascript - 七吃九 : Why is my index 8 being skipped in this d3 selection?

标签 javascript d3.js svg

我正在编写一个包含函数 drawWorkingLife 的 D3 脚本,该函数将 11 个图像附加到 SVG。我注意到脚本跳过了附加第 8 个图像。

为了调试,我可以看到,如果我在为图像添加 x 和 y 属性的地方使用 console.log,则不会记录索引 8。

在下面的 drawWorkingLife 函数中,为什么索引号 8 没有记录到控制台?

演示:http://radiocontrolled.github.io/sevenAteNine
repo :https://github.com/radiocontrolled/sevenAteNine

function drawWorkingLife() {
 var work = svg.selectAll("image")
  .data(workingLife, function(d,i) { 
    return d[i]; 
  })
  .enter()
  .append("g");

  work
  .append("svg:image")
  .attr(opts)
  .attr({
    "x" : function(d,i) {
      console.log(i);
      // why is index 8 skipped? 

    },
    "y" : function(d,i) {
      console.log(i);
      // why is index 8 skipped? 
    },       
    "class" : function(d,i){
      return d;
    }
  })
  .transition()
  .duration(1000)
  .style("opacity", 1);

最佳答案

问题出在将数据与选择相关联的代码中:

.data(workingLife, function(d,i) { 
  return d[i]; 
})

该调用的第二个参数是一个函数,它告诉 D3 如何唯一标识每个数据值。您正在返回数据的第 i 个字符(在您的示例中它们都只是一个字符串)。您的字符串都是“workingLife”,并且“i”字符在该字符串中出现了两次。因此,您已经告诉 D3 数据值 4 和数据值 8 相同。因此,D3 认为第 8 个值是重复的。

关于javascript - 七吃九 : Why is my index 8 being skipped in this d3 selection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109231/

相关文章:

javascript - 在 javascript 中正确获取 json

javascript - 使用@method 或@property 的JSDoc 对象方法?

javascript - D3 : dataset update does not remove elements from DOM

javascript - 当我想画和弦时,在 d3 v4 中遇到一些麻烦

html - 更改 SVG 图像在帧内的位置

javascript - 如果 URL 后面有查询字符串,则使用 javascript 更改文件扩展名

圆角为圆弧的 SVG 路径

javascript - 键盘快捷键扩展中的触发事件

javascript - 如何使用 hibernate、spring mvc 和 angular js 从后端检索图像和其他数据并显示在屏幕上?

javascript - 如何访问 D3.js 版本 4 中的节点 x 和 y?