1

i played with this example of a force directed graph layout. www.bl.ocks.org/GerHobbelt/3071239

or to manipulate directly, here with fiddle, http://jsfiddle.net/BeSAb/

what i want was to replace the circle element

  node = nodeg.selectAll("circle.node").data(net.nodes, nodeid);
  node.exit().remove();

  node.enter().append("circle")
      .attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
      .attr("r", function(d) { return d.size ? d.size + dr : dr+1; })
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .style("fill", function(d) { return fill(d.group); })
      .on("click", function(d) {
        console.log("node click", d, arguments, this, expand[d.group]);
        expand[d.group] = !expand[d.group];
    init();
      });

with a group (g) element that contains a svg foreignObject

node = nodeg.selectAll("g.node").data(net.nodes, nodeid);
node.exit().remove();

var nodeEnter = node.enter().append("foreignObject")
//simplified for this demo
        .attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
        .attr('width', '22px')
        .attr('height', '22px')
        .attr('x', -11)
        .attr('y', -11)
        .append('xhtml:div')
            .style("background",function(d){return fill(d.group)})
            .style("width","20px")
            .style("height","20px")
            .style("padding","2px")
       .on("click", function(d) {
       console.log("node click", d, arguments, this, expand[d.group]);
       expand[d.group] = !expand[d.group];
       init();
       });

The Graph is build correct but if i try to expand a node by clicking it, it seems that the graph isn't updated. So that all old nodes are duplicated.

i make an other Fiddle where you can show this problem by clicking a node. http://jsfiddle.net/xkV4b/

does anyone know what i forgot, or what the issue is?

Thank you very much!

4

1 回答 1

1

Your enter append should probably match your selection on nodeg. But even then it appears that d3 has some trouble selecting 'foreignObject' things. That may be a question/issue to bring up on the d3 google group - it may be a bug.

However you can get around it by just selecting on the class. I updated the code to read:

node = nodeg.selectAll(".fo-node").data(net.nodes, nodeid);
node.exit().remove();

var nodeEnter = node.enter().append("foreignObject")
    .attr("class", function(d) { return "fo-node node" + (d.size?"":" leaf"); })
    .attr('width', '22px')
    ...

Which seems to work.

于 2013-03-04T23:54:20.100 回答