从文件加载后,D3.js代码无法在浏览器中呈现,但在控制台中可以正常工作 [英] D3.js code not rendering in browser when loaded from file, but works fine in console
问题描述
我正在使用Rails 4.0beta,并且在主体部分的底部有以下d3.js脚本.直接粘贴到Chrome开发者工具控制台中时,代码将生成图形.但是,如果它只是从服务器发送来呈现页面的文件中的脚本,则它不会生成图形.有人知道为什么吗?我一定是在犯一个简单的错误……只是不知道在哪里.
I'm using Rails 4.0beta and I have the following d3.js script at the bottom of the body section. When pasted directly into the Chrome developer tools console, the code generates the graph. But if it is just as a script in the file that gets sent from the server to render the page, it doesn't generate the graph. Anyone know why? I must be making some simple mistake ... just can't figure out where.
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js">
function generateGraph() {
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);
var valueline = d3.svg.line().x(function(d) { return x(d.date); }).y(function(d) { return y(d.load_volume); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("/users/5/workouts/analyze.json", function(error, data) {
data.forEach( function (d) {
d.date = parseDate(d.date);
d.load_volume = +d.load_volume;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.load_volume; })]);
svg.append("path").attr("d", valueline(data)); // Add the valueline path
svg.append("g").attr("transform", "translate(0," + height + ")") .call(xAxis); // Add the X Axis .attr("class", "x axis")
svg.append("g").attr("class", "y axis").call(yAxis); // Add the Y Axis
});
};
generateGraph();
</script>
推荐答案
您正试图将库包含在包含代码的script标记中.尝试改用它:
You are trying to include the library in the script tag that contains your code. Try to use this instead:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// your code here
</script>
这篇关于从文件加载后,D3.js代码无法在浏览器中呈现,但在控制台中可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!