无法将外部Javascript与D3JS链接

时间:2015-11-30 16:49:21

标签: javascript html d3.js

请参阅think plunk:http://plnkr.co/edit/2lvNHxvLEsNpVqNqmDUX?p=preview

我试图用D3JS使用javascript绘制一个圆圈。我的script.js文件定义了圆圈。

    d3.select("body")
  .append("svg")
    .attr("width",50)
    .attr("height",50)
  .append("circle")
    .attr("cx",25)
    .attr("cy",25)
    .attr("r",25)
    .style("fill","purple");

但它并没有出现在D3圈标题之后的html中。有人能告诉我我做错了吗?

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@*" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <title>D3JS Demo - Drawing Shapes</title>
  </head>

  <body>
    <h3>SVG Bar</h3>
    <svg>
      <rect width="50" height="200" style="fill:blue"></rect>
    </svg>

    <h3>D3 Bar</h3>
    <script>
      d3.select("body")
        .append("svg")
        .append("rect")
          .attr("widt ah",50)
          .attr("height",200)
            .style("fill","blue");
    </script>

    <h3>SVG Circle</h3>
    <svg width="50" height="50">
      <circle cx="25" cy="25" r="25" style="fill:blue"></circle>
    </svg>

    <h3>D3 Circle</h3>

  </body>

</html>

1 个答案:

答案 0 :(得分:2)

您需要在script之后添加h3,而不是head,如下所示:

<h3>D3 Circle</h3>
<script src="script.js"></script>

您的body正在执行时尚未存在script个元素。这意味着如果脚本在头部运行,d3.select("body")将为空。

http://plnkr.co/edit/Xofci5Rm9XdpsP1zqu8a?p=preview

相关问题