Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - Elements appended to SVG with D3 are not appearing

I am trying to display some simple bar charts with D3 where each bar is a div, but nothing is being displayed.

var chartData =  [4, 8, 15, 16, 23, 42];
var body = d3.select('body');
    
var svg = body.append('svg')
   .attr("width",800)
   .attr("height",500);
    
var div = svg.append('div').attr('class', '.chart');
    
for (var i = 0; i < chartData.length; i++) {
   div.append('div')
    .attr("height", 20)
    .attr("width", chartData[i]*10)
    .html(chartData[i]);
}
.chart div {
font: 10px sans-serif;
  background-color: steelblue;
text-align: right;
padding: 3px;
  margin: 1px;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In a nutshell: you cannot append a HTML element to a SVG. The reason is simple: <div>, <p>, <h1>, <h2>, <td>, <li> and so on are not valid SVG elements.

This has been asked and answered many, many times. However, I'd like to answer this question because of a specific part of it (which is normally not asked):

When using chrome's inspect I see the newly created elements.

Yes, the elements are there. But this doesn't mean it's going to work.

Let's show this in the following snippet, in which I'm appending <div>s to the SVG. look at the console.log, it shows the SVG structure:

var svg = d3.select("svg");

var data = d3.range(5);

var divs = svg.selectAll("foo")
.data(data)
.enter()
.append("div")
.html("Where are you?")

var mySVG = (new XMLSerializer()).serializeToString(svg.node());
console.log(mySVG)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...