javascript - d3js 给出类型错误 "d is undefined"

标签 javascript d3.js

我构建了一个 d3 map ,并且必须访问各种操作的绑定(bind)数据。当我使用 .on("mouseover",...).on("mousemove",...) 执行此操作时,效果很好。但我也想根据这些值设置填充颜色。当我尝试通过 .attr("fill",...) 和回调函数执行此操作时,它给了我一个 typeError“d is undefinded”。这是一个工作和非工作代码示例:

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .on("mouseover",function (d){ 

        // gives me the correct values
        console.log(d.properties.AGS) 

    })

非工作:

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .attr("fill",function (d){ 

        // gives me TypeError: d is undefined
        console.log(d.properties.AGS)

        // the same here
        console.log(d.properties)

    })

记录根元素再次起作用

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .attr("fill",function (d){ 

        console.log(d)
        // works and gives me a list of objects:
        // Object { type: "Feature", properties: Object, geometry: Object }
        // Object { type: "Feature", properties: Object, geometry: Object }
        // Object { type: "Feature", properties: Object, geometry: Object }
        // ...

    })

最佳答案

我的 geojson 生成了一些没有属性和坐标的对象(无论它们来自哪里......),因此它们在屏幕上不可见,但在 DOM 中退出。在我写了一个小语句来检查是否定义了属性之后,它起作用了!

kommunen
.selectAll("path")
.data(featuresKommunen)
.enter().append("path")
.attr("d", path)
.attr("class", "kommune")
.attr("fill",function (d){

   // works by skipping the missing properies-values
   if (d.properties) {console.log(d.properties.AGS)}

})

关于javascript - d3js 给出类型错误 "d is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503372/

相关文章:

javascript - 如何在 c3js 饼图上绘制自定义 JSON 数据?

javascript - 抛出与从服务类返回错误

javascript - 根据预选用值填充选择列表

javascript - Vue.js 不渲染组件

javascript - d3.js 继续条件加载数据

javascript - 仅当我在最后写入 Enter() 时图形才会更新

javascript - 在 NodeJS 上实现高性能代理

d3.js 将比例调整为蓝色的 rgb() 范围

javascript - 无法从 d3 json 文件中读取路径 d 值?

javascript - 如何在 d3 中悬停时增加饼图的大小