Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - d3.select method not working

I am new to datavis and the D3 library and I'm trying to follow the tut here http://mbostock.github.com/d3/tutorial/bar-1.html

When I run the code, nothing displays on my webpage, can anyone point out the problem??

I think its something to do with the d3.select method. When I run the code and inspect it, the body is empty, so Im assuming nothing is being created. Any help would be hugely appreciated!!!

<title>3Dtut - 1</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.4.5">   </script>

<script type="text/javascript">
var data = [4, 8, 15, 16, 23, 42];  

//container for the bar chart
var chart = d3.select("body").append("div")
.attr("class", "chart");

//adding div elements to the bar chart
 chart.selectAll("div")
     .data(data)
     .enter().append("div")
     .style("width", function(d) { return d * 10 + "px"; })
     .text(function(d) { return d; });
</script>


<STYLE type="text/css">
.chart div {
   font: 10px sans-serif;
   background-color: steelblue;
   text-align: right;
   padding: 3px;
   margin: 1px;
   color: white;
 }
 </STYLE>
</head>
<body>
</body>
</html>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The problem is related to the position of your <script> .. </script> within the html document.

No body element exists yet at the moment that your script is being executed. That means that d3.select("body") will be empty, and no div.chart is being appended.

Try to move your <script> .. </script> inside the <body> .. </body> part. This will guarantee that the body element exists when your code is being executed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...