D3 v3 appending checkbox?

心已入冬 提交于 2021-02-19 05:26:57

问题


Am working with collapsible tree top to bottom orientatin. Here i stuck with some problem. To implement the tree am using d3.v3.js. How can i append check box into the tree for each node.

    // Create the link lines.
    svg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.svg.diagonal().projection(function(d) { return [o.x(d)+15, o.y(d)]; }));

        svg.selectAll("input")
        .data(nodes)
        .enter().append("foreignObject")
        .attr('x' , o.x)
        .attr('y',  o.y)
        .attr('width', 50)
        .attr('height', 20)
        .append("xhtml:body")
        .html("<form><input type=checkbox id=check></input></form>")
     .on("click", function(d, i){
            console.log(svg.select("#check").node().checked) 
            }) ;

    svg.selectAll("image")
        .data(nodes)
     .enter().append("image")
        .attr('x' , o.x)
        .attr('y',  o.y)
        .attr('width', 30)
        .attr('height', 20)
        .attr("xlink:href", "check.png")
  }); 
});

Checkbox in appending in to svg but not been visible in browser. Anybody please help me to solve this issue


回答1:


You need to be creating a holder for the foreignObjects (i.e. checkbox's) and not the inputs in this line:

svg.selectAll("input")

which should be

svg.selectAll("foreignObject")

you then need to drive the number of checkbox's with the data as in, data(data) and bind it with the enter(), as you've done. If you want multiple elements to appear you need to use dynamic variable for the x and y. In a simple example that would be .attr('x', function (d,i) { return d.x; }). So putting it all together in a fiddle you get this.




回答2:


Your checkbox does not appear because you cannot append arbitrary html elements to svg. You should use either < g > or floating elements:

#canvas {
  position: relative;
}

Then append checkbox element using:

d3.select("#canvas")
  .append("input")
  .attr("type", "checkbox")
  .style("position", "absolute")
  .style("top", "320")
  .style("left", "150")



回答3:


This answer is more usefull those are using Bootstrap.To append checkbox in bootstrap we need to specify label and span expectly while appending foreign object. Otherwise it not be visible in browser

 svg.selectAll("foreignObject")
   .data(nodes).enter()
   .append("foreignObject")
   .attr('x', o.x)
   .attr('y',  o.y)
   .attr('width', 30)
   .attr('height', 20)
   .append("xhtml:tree")
   .html("<label class='inline'><input type='checkbox'><span class='lbl'> </span>               </label>");


来源:https://stackoverflow.com/questions/19263476/d3-v3-appending-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!