[英]Simple D3js code not working
我正在运行一个简单的d3js代码(第一个来自此处 )。 当我从.html文件中的script标记运行js代码时,它可以正常工作,但是如果我将js代码移至.js文件并将其包含在.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>
该代码不起作用:
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
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");});
有人可以解释这种行为吗?
我认为代码是在HTML解析之前运行的。
您应该尝试始终将代码包装在dom内容加载的侦听器中。 然后它将在所有的html和css解析之后执行。
document.addEventListener('DOMContentLoaded', function() {
// ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.