简单的D3js代码不起作用

时间:2014-10-24 14:46:27

标签: javascript html d3.js

我正在运行一个简单的d3js代码(来自here的第一个代码)。当我从.html文件中的脚本标记运行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");});

有人可以解释这种行为吗?

1 个答案:

答案 0 :(得分:0)

我认为代码是在解析HTML之前运行的。

您应该尝试始终将代码包装在dom内容加载的侦听器中。 然后在解析所有html和css之后执行它。

document.addEventListener('DOMContentLoaded', function() {
    // ...
});