[英]Simple D3js code not working
I'm running a simple d3js code (the first one from here ). 我正在运行一个简单的d3js代码(第一个来自此处 )。 When I run the js code from the script tag in the .html file, it works fine but if I move the js code to a .js file and include that in the .html file, it doesn't work.
当我从.html文件中的script标记运行js代码时,它可以正常工作,但是如果我将js代码移至.js文件并将其包含在.html文件中,则它将无法正常工作。
This code works: 此代码有效:
index.html index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);
sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");});
</script>
</body>
</html>
This code doesn't work: 该代码不起作用:
index.html index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="viz"></div>
</body>
</html>
app.js app.js
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);
sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");});
Can someone explain this behavior? 有人可以解释这种行为吗?
I think the code is run before the HTML is parsed. 我认为代码是在HTML解析之前运行的。
You should try to always wrap your code in a dom content loaded listener. 您应该尝试始终将代码包装在dom内容加载的侦听器中。 Then it will be executed after all the html and css is parsed.
然后它将在所有的html和css解析之后执行。
document.addEventListener('DOMContentLoaded', function() {
// ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.