问题
I have followed the various examples from Mike Bostock to create a collapsible force layout with directed paths and images at the nodes (related to this other question).
Now, I want to link some extra information to some of the nodes if they contain any extra information, as structured by the data in a json string.
The json string that looks like this:
{
"name": "Somename",
"text": "Some text",
"extradata": [
{
"type": "sometype",
"icon": "someicon.png"
},
{
"type": "sometype02",
"icon": "someicon.png"
}
],
"children": [
{
"name": "Somename",
"text": "Some text",
"extradata": [
{
"type": "sometype",
"icon": "someicon.png"
},
]
},
{
"name": "Somename",
"text": "Some text",
"extradata": [
{
"type": "sometype",
"icon": "someicon.png"
},
{ .... },
{ .... },
{ .... },
....
],
"children": [
{
....
}
},
........
In short, I would like to display some of the values of the extradata[]
array linked to every node that this extradata attribute. The end result would look something like the image below, where the blue circles represent the contents from extradata (e.g sometype
or sometype02
).
I'm having trouble understanding how to parse the json string in order to get to those values, and how to create the links to the nodes where they belong.
回答1:
The beauty of d3 is that the Javascript objects are intrinsically linked to the DOM objects that represent them. You might even say the data drives the document.
Presumably you have something like this:
var node = svg.selectAll(".node")
.data(data.nodes)
.enter().append("circle")
[...]
Maybe you want to color each node according to the first datatype
property in the JSON:
var node = svg.selectAll(".node")
.data(data.nodes)
.enter()
.append("circle")
.style("fill", function(d) {
return d.extradata[0].type === "sometype" ? "#FF0000" : "#0000FF";
})
Point is, you already have access to the object in the d
variable passed to the function.
Here's an example of using the FDL and coloring nodes from a data property. Also includes tooltips.
来源:https://stackoverflow.com/questions/16481570/how-to-link-extra-attributes-from-json-data-in-a-d3-js-force-layout