在D3中设置多个属性而又不知道它们会提前 [英] set multiple attributes in D3 without knowing what they are going to be ahead of time
问题描述
我想在d3中设置多个属性,类似于在此答案中所做的操作: https://stackoverflow.com/a/20822552/1112097 ,但是我希望能够将一组属性作为数组传递,以便同一代码可以创建不同的元素.例如,以下数据应创建一个红色正方形和一个绿色圆圈:
I am tying to set multiple attributes in d3 similar to what is done in this answer: https://stackoverflow.com/a/20822552/1112097, but I want to be able to pass a set of attributes in as an array so that the same code can create different elements. For example, the following data should create a red square and a green circle:
var data = [
{
name: "Element 1",
type: "rect",
id: "rect01",
attributes: [
{label: "x", val: 0},
{label: "y", val: 0},
{label: "width", val: 10},
{label: "height", val: 10},
],
styles: [
{label: "fill", val: "none"},
{label: "stroke", val: "#ff0000"}
]
},
{
name: "Element 2",
type: "circle",
id: "circle01",
attributes: [
{label: "cx", val: 30},
{label: "cy", val: 30},
{label: "r", val: 10}
],
styles: [
{label: "fill", val: "#00ff00"},
{label: "stroke", val: "#0000ff"}
]
}
];
使用如下所示的内容:
var element = svg.selectAll(".element")
.data(data, function(d) {return d.id;});
var elementEnter = element.enter()
.append(function (d) {return d.type;})
.attr("class", "element")
.attr({
// what goes here?
})
.style({
// what goes here?
}):
我可以用什么代替这里发生了什么?"使用数据数组设置属性(例如"x","cx"或"r")和值.
What can I put in place of "what goes here?" to set both the attribute (e.g. 'x', 'cx' or 'r') and the value using the data array.
推荐答案
尝试一下.
function setAttributesAndStyles(d){
var attrs = {};
d.attributes.forEach(function(a){
attrs[a.label] = a.val;
});
var styles = {};
d.styles.forEach(function(a){
styles[a.label] = a.val;
});
d3.select(this).attr(attrs);
d3.select(this).attr(styles);
}
var element = svg.selectAll(".element")
.data(data, function(d) {return d.id;});
var elementEnter = element.enter()
.append(function (d) {
return svg.append(d.type).node(); //Returns the dom element
})
.attr("class", "element")
.each(setAttributesAndStyles);
请注意,selection.append(name)
语句希望名称为常量字符串或返回要附加的DOM元素的函数.
Note that selection.append(name)
statement expects the name as a constant string or a function that returns the DOM element to append.
这篇关于在D3中设置多个属性而又不知道它们会提前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!