简体   繁体   English

我无法选择已从外部加载到D3中的SVG的元素

[英]I can't select elements of an SVG I've loaded externally into D3

I'm trying to load an external SVG into D3 and then be able to select and manipulate using D3 functions. 我正在尝试将外部SVG加载到D3中,然后能够使用D3函数进行选择和操作。 I was able to get it loaded on the page with the following code: 我能够使用以下代码将其加载到页面上:

  d3.xml("external.svg").mimeType("image/svg+xml").get(function(error, xml) {
    if (error) throw error;
    document.body.appendChild(xml.documentElement);                        
  })

However, when I try to use d3.select, none of the functions work. 但是,当我尝试使用d3.select时,所有功能都不起作用。 When I console.log the selected element, it shows an empty array. 当我console.log选定的元素时,它显示一个空数组。

Based on the plunkr you provided, in order for your events to work properly, you need to add them after d3 has loaded the svg. 根据您提供的插件 ,为了使事件正常运行,您需要在d3加载svg之后添加事件。 So, instead of this: 因此,代替此:

d3.xml("DCMetroMap.svg").mimeType("image/svg+xml").get(function(error, xml) {
    if (error) throw error;
    document.body.appendChild(xml.documentElement);
  })

  // this runs before the above finishes, so d3 won't find something to select
  d3.select("#K05")
    .on("mouseover", function(d) {
      console.log(d)
      console.log('hello')
    })

   console.log(d3.select("#K05"))

You need to move the select like this: 您需要像这样移动选择:

  d3.xml("DCMetroMap.svg").mimeType("image/svg+xml").get(function(error, xml) {
    if (error) throw error;
    // load the document 
    document.body.appendChild(xml.documentElement);

    //then add the events
    d3.select("#K05")
    .on("mouseover", function(d) {
      console.log(d) // d will be null here
      console.log('hello')
      alert("Hi!")

    })

  })

Like this: http://plnkr.co/edit/WbYyBKtzZe6MtKGbjzw9?p=preview 像这样: http : //plnkr.co/edit/WbYyBKtzZe6MtKGbjzw9?p=preview

In other words, anything you do, you must put it after document.body.appendChild(xml.documentElement); 换句话说,无论您做什么,都必须将其放在document.body.appendChild(xml.documentElement);之后document.body.appendChild(xml.documentElement);

Hope this helps! 希望这可以帮助! Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM