这个问题更多的是为了满足我自己的好奇心。我想知道如何使用 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>
所以这是一个经典的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>
为了绝对确定,请听DOMContentLoaded
喜欢
document.addEventListener('DOMContentLoaded', function(){
init();
})
function init(){
var svg = d3.select("svg");
var circle = svg.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 20)
.style("color", "green");
}
此时,您可以更灵活地选择与页面和目标元素相关的脚本注入的时间和位置