簡體   English   中英

如何在D3中選擇現有的SVG容器而不使用D3創建該容器?

[英]How to select an existing SVG container in D3 without creating that container using D3?

這個問題比其他任何事情都更能滿足我的好奇心。 我想知道如何使用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代碼從頭部移到結束body標簽之前。

 <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");
}

此時,您可以更靈活地在何時何地相對於頁面以及目標元素注入腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM