无法通过其ID访问SVG [英] Can't access SVG by its ID
问题描述
我想在文件加载后访问svg及其路径的id以进行交互式使用。我使用函数加载SVG并将节点导入DOM。在document.ready 中也没有在document.addEventListener(DOMContentLoaded,function(event))中,我可以通过其id获取元素。获取它的唯一方法要在互动代码周围设置超时。
I want to access the id of the svg and its paths after the file has loaded for interactive use. I load the SVG with a function and import the node to the DOM. Neither in document.ready nor in document.addEventListener("DOMContentLoaded", function(event) i am able to get the element by its id. The only way to get it is to set a timeout around the interactive code.
我想要的是SVG(900kb)及其DOM应该在所有其他代码加载之前加载,但到现在为止我找不到一个fiting的解决方案。
What i want is that the SVG (900kb) und its DOM should load before all other code is loaded. But until now i couldn find a fiting solution.
我很困惑,因为如果我在浏览器中看到DOM,我可以看到与ID的div,但我不能得到它....我无法找到一个问题在我的代码,因为我加载它在DOM中,并在DOM准备好后访问
任何人在这里找到解决方案?
I am very confused because if i look at the DOM in the browser with firebug i am able to see the div with the ID but i cant get it .... And i cant find a issue in my code because i load it in the DOM and access it after DOM is ready ? Anyone here who find a solution?
这是我加载svg的代码:
This is my code to load the svg:
function fetchXML (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
if (xhr.readyState === 4) {
callback(xhr.responseXML);
}
};
xhr.send(null);
};
fetchXML("svg/bez_grey.svg",function(newSVGDoc){
var n = document.importNode(newSVGDoc.documentElement,true);
var mysvg = document.getElementById("map");
mysvg.appendChild(n);
})
document.addEventListener("DOMContentLoaded", function(event) {
// Access the SVG-Elements here
}):
推荐答案
您需要调用 document.documentElement.appendChild(n);
$ c> var mysvg = document.getElementById(map); 。将 n
加载到文档
的DOM中。您可以删除语句 mysvg.appendChild(n);
You need to call document.documentElement.appendChild(n);
before calling var mysvg = document.getElementById("map");
. This loads n
into document
's DOM. You can delete statement mysvg.appendChild(n);
此解决方案基于这里的工作代码示例: a href =https://stackoverflow.com/a/3378320> https://stackoverflow.com/a/3378320
This solution is based on working code example here: https://stackoverflow.com/a/3378320
这篇关于无法通过其ID访问SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!