admin管理员组

文章数量:1307752

Using the force layout in d3, I can happily add nodes as, say, an SVG group of a circle and some text:

var node = vis.selectAll(".node")
    .data(nodes)
    .enter().append("svg:g")
    .attr("class", "node");
node.append("svg:circle")
    .attr("r", 5);
node.append("svg:text")
    .text(function(d) { return d.nodetext });

However, I would like to optionally add another element to the group, dependent on the node data: so if the data for this node contains an "image" attribute, I'd like to add a new child-element (an svg:image). It's easy to add the svg:image to all nodes (I just do it as I've done the circle and text above). It's also easy to dynamically change an attribute of an element you've already created (by having a function as the attribute's value, as per text above). I do not know how to add an svg:image child element only if the data contains an image attribute. What's the best way of achieving this?

Using the force layout in d3, I can happily add nodes as, say, an SVG group of a circle and some text:

var node = vis.selectAll(".node")
    .data(nodes)
    .enter().append("svg:g")
    .attr("class", "node");
node.append("svg:circle")
    .attr("r", 5);
node.append("svg:text")
    .text(function(d) { return d.nodetext });

However, I would like to optionally add another element to the group, dependent on the node data: so if the data for this node contains an "image" attribute, I'd like to add a new child-element (an svg:image). It's easy to add the svg:image to all nodes (I just do it as I've done the circle and text above). It's also easy to dynamically change an attribute of an element you've already created (by having a function as the attribute's value, as per text above). I do not know how to add an svg:image child element only if the data contains an image attribute. What's the best way of achieving this?

Share Improve this question edited Jun 3, 2014 at 11:06 VividD 10.5k8 gold badges66 silver badges112 bronze badges asked Oct 8, 2012 at 18:57 silsil 2,1291 gold badge23 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

Try selection.filter:

node.filter(function(d) { return d.image; }).append("image")
    .attr("xlink:href", function(d) { return d.image; })
    .attr("width", 16)
    .attr("height", 16);

本文标签: javascriptd3 Optionally add child elements based on node content in force layoutStack Overflow