我想根据数据中提供的类型将“图标”(路径,矩形或圆形元素)附加到我的输入选择中。有人有什么想法吗?
var data = [
{
type: "apple" // -> Icon should be a rect
text: "Demo"
},
{
type: "banana" // -> Icon should be a circle
text: "Demo"
},
{
type: "peach" // -> Icon should be a path
text: "Demo"
},
{
type: "pear" // -> Icon should be a rect
text: "Demo"
},
];
d3.selectAll(".fruit")
.data(data)
.enter()
.each(function(d, i) { // <- Each is not a function of enter selection
switch(d.type) {
case "apple":
var type = "rect";
break;
case "banana":
var type = "circle";
break;
case "peach":
var type = "path";
break;
case "pear":
var type = "rect";
break;
default:
var type = "rect";
break;
}
this.append(type);
});
我的示例不起作用,因为.each()不是输入选择的功能。有人有想法吗?
THX
答案 0 :(得分:0)
为什么要尝试使用.each
完成此任务。您可以在使用纯javascript绑定到dom元素之前处理数据。
var data = [{
type: "apple",
text: "Demo"
}, {
type: "banana",
text: "Demo"
}, {
type: "peach",
text: "Demo"
}, {
type: "pear",
text: "Demo"
}, ];
data.forEach(function(d) {
switch (d.type) {
case "apple":
var type = "rect";
break;
case "banana":
var type = "circle";
break;
case "peach":
var type = "path";
break;
case "pear":
var type = "rect";
break;
default:
var type = "rect";
break;
}
d.icon = type;
});
console.log(data); //Now, each object will contain icon property according to it's type
var selection = d3.selectAll(".fruit")
.data(data)
.enter();