我有一个像这样的JSON数组:
{
"nodes":[
{"id":"x", "style":[
{"shape":"circle","value":"10","fill":"red"}]
},
....
....
],
"links":[
{"source":"x", "target":"y"},
....
....
]
}
我想从“样式”字段中获取数据。 如果你写这样的代码
,它就不起作用var node = svg.append("g")
.attr("class", "nodes")
.selectAll("g")
.data(graph.nodes)
.enter().append("g")
.attr("fill",function(d){return(d.style.fill) })
我该怎么办?
答案 0 :(得分:0)
根据您的数据的一般示例,
<div id="one" (click)="two.style.background = (two.style.background == 'grey') ? 'white' : 'red'">BB</div>
<div id="two" #two>AA</div>
要获得&#39; fill&#39;的价值,您需要像这样编码
var data = { "nodes":[ {"id":"x", "style":{"shape":"circle","value":"10","fill":"red"} } , {"id":"y", "style":{"shape":"square","value":"20","fill":"blue"} } ], "links":[ {"source":"x", "target":"y" } ] };
和
data.nodes[0].style.fill
答案 1 :(得分:0)
由于您的style
是一个只有一个对象的数组,您必须使用[0]
选择此数组:
.style("fill", d => d.style[0].fill);
这是一个演示。在这个片段中,我使用了这个数据结构:
var graph = { nodes: [{
name: "a",
style: [{ "shape": "circle", "value": "10", "fill": "red"}]
}, {
name: "b",
style: [{ "shape": "circle", "value": "10", "fill": "blue"}]
}, {
etc...
哪个与你的相似。检查一下(我使用D3 v3.x):
var graph = {
nodes: [{
name: "a",
style: [{
"shape": "circle",
"value": "10",
"fill": "red"
}]
}, {
name: "b",
style: [{
"shape": "circle",
"value": "10",
"fill": "blue"
}]
}, {
name: "c",
style: [{
"shape": "circle",
"value": "10",
"fill": "teal"
}]
}, {
name: "d",
style: [{
"shape": "circle",
"value": "10",
"fill": "green"
}]
}, {
name: "e",
style: [{
"shape": "circle",
"value": "10",
"fill": "silver"
}]
}, {
name: "f",
style: [{
"shape": "circle",
"value": "10",
"fill": "orange"
}]
}],
links: [{
source: 1,
target: 0,
}, {
source: 2,
target: 0,
}, {
source: 3,
target: 0,
}, {
source: 4,
target: 0,
}, {
source: 5,
target: 0,
}]
};
var width = 400
height = 300;
var force = d3.layout.force()
.nodes(graph.nodes)
.links(graph.links)
.size([width, height])
.linkDistance(50)
.charge(-1000)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("stroke", "black")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", (d, i) => i ? 10 : 16)
.style("fill", d => d.style[0].fill);
function tick() {
link.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
});
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;