d3 基本附加示例不起作用

use*_*110 5 append d3.js

我只是从 d3 而不是通常的 jquery 开始,但即使他们的基本示例似乎也没有实际附加任何内容。我的任何部分标签中都没有添加任何内容:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Test</title>
  <meta name="description" content="stats">
</head>

<body>
    <script type="text/javascript"src="js/d3.min.js"></script>
  <script type='text/javascript'>
var section = d3.selectAll("section");

section.append("div")
    .html("First!");

section.append("div")
    .html("Second.");
  </script>
<section>asfd</section>
<section>erasdf</section>
<section>asdfq</section>
<section>asdfasdfas</section>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Pbk*_*303 4

您的附加不起作用<section>的原因是因为您先添加了脚本,然后添加了脚本。由于脚本标记是第一个,因此脚本将首先执行,执行时selectAll("section")它会搜索要附加的部分标记,但它不存在,因为部分标记位于脚本之后。为了使其正常工作,请将脚本移至底部

HTML:

<!doctype html>    
<html lang="en">
<head>
  <meta charset="utf-8">    
  <title>Test</title>
  <meta name="description" content="stats">
</head>

<body>

<section>asfd</section>
<section>erasdf</section>
<section>asdfq</section>
<section>asdfasdfas</section>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>

 <script type="text/javascript"src="js/d3.min.js"></script>
 <script type='text/javascript'>
var section = d3.selectAll("section");

section.append("div")
    .html("First!");

section.append("div")
    .html("Second.");
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)