我构建了一个 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/