如何在 D3 中选择现有的 SVG 容器而不使用 D3 创建该容器?

Omn*_*ous 0 html javascript svg d3.js

这个问题更多是为了满足我自己的好奇心,而不是其他任何事情。我想知道如何使用 d3 选择已经存在于 HTML 文档正文中的 SVG 元素,而无需先使用 d3 创建该 SVG 元素。我希望以下代码段可以工作,但它不起作用,这让我感到非常沮丧。

<html lang="en">

    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js">
    </script>
    <script type="text/javascript">

      // If the below is changed to append instead of select it works
      // but what if I don't want to create the SVG using d3
      var svg = d3.select("body").select("svg")


      var circle = svg.append("circle")
          .attr("cx", 50)
          .attr("cy", 50)
          .attr("r", 20)

    </script>
    <style>



    </style>


  </head>


  <body>

  <svg>
  </svg>

  </body>


</html>
Run Code Online (Sandbox Code Playgroud)

Nic*_*ova 5

所以这是一个经典的 JavaScript 问题。它无法正常工作,因为页面元素尚未完成加载。解决方法是将 d3 代码从头部移动到结束正文标记之前。

<html lang="en">

    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js">
    </script>

    <style>



    </style>


  </head>


  <body>

  <svg>
  </svg>

    <script type="text/javascript">

      // If the below is changed to append instead of select it works
      // but what if I don't want to create the SVG using d3
      var svg = d3.select("body").select("svg");


      var circle = svg.append("circle")
          .attr("cx", 50)
          .attr("cy", 50)
          .attr("r", 20)
          .style("color", "green");

    </script>

  </body>


</html>
Run Code Online (Sandbox Code Playgroud)