从SVG中的路径获取ID

时间:2019-03-07 21:35:05

标签: javascript svg

所以我有这个SVG

https://github.com/Cphdat3sem2017f/StartcodeExercises/blob/master/JS/Countries_Europe.svg?short_path=6bcbfa5

我设法连接了一个eventListener和一个fetch以获取有关单击时所在国家/地区的信息。我可以通过简单地致电ex来完成。 document.getElementById(“ dk”)。有没有一种方法,如果可以的话,如何在路径中获取ID,以便我可以遍历它们并最终只打一个电话,而不是每个国家打一个电话?

代码:

import "bootstrap/dist/css/bootstrap.css";

const root = document.getElementById("root");
var svg = document.getElementById("svg");

const country = "https://restcountries.eu/rest/v1/alpha?codes=";

svg.addEventListener("load", function() {
  var svgDoc = svg.contentDocument;

  var countries = svgDoc.children;
  for (let i = 0; i < countries.length; i++) {
    //alert(countries[i].id);
    countries[i].addEventListener("click", function(event) {
      alert(countires[i]);
      getCountryInfo(countries[i].id);
    });
  }

  svgDoc.addEventListener("click", function(event) {
    getCountryInfo(event.id);
  });

  var denmark = svgDoc.getElementById("dk");
  denmark.addEventListener("click", function() {
    getCountryInfo("dk");
  });

  var sweden = svgDoc.getElementById("se");
  sweden.addEventListener("click", function() {
    getCountryInfo("se");
  });

  var germany = svgDoc.getElementById("de");
  germany.addEventListener("click", function() {
    getCountryInfo("de");
  });

  var norway = svgDoc.getElementById("no");
  norway.addEventListener("click", function() {
    getCountryInfo("no");
  });

  var spain = svgDoc.getElementById("es");
  spain.addEventListener("click", function() {
    getCountryInfo("es");
  });

  var iceland = svgDoc.getElementById("is");
  iceland.addEventListener("click", function() {
    getCountryInfo("is");
  });
});

function getCountryInfo(landCode) {
  fetch(country + landCode)
    .then(res => res.json()) //.then(res=>{ return res.json()})
    .then(data => {
      var table = "";
      table +=
        '<table border="1" style="border-spacing: 5px; table-layout: auto; width: 45%;">';
      table += "<tr>";
      table += "<th>Name</th>";
      table += "<th>Capital</th>";
      table += "<th>Also known as</th>";
      table += "<th>Region</th>";
      table += "<th>Population</th>";
      table += "<th>Languages</th>";
      table += "</tr>";
      data.forEach(country => {
        table += "<tr>";
        table += "<td>" + country.name + "</td>";
        table += "<td>" + country.capital + "</td>";
        table += "<td>" + country.altSpellings + "</td>";
        table += "<td>" + country.region + "</td>";
        table += "<td>" + country.population + "</td>";
        table += "<td>" + country.languages + "</td>";
        table += "</tr>";
      });
      table += "</table>";
      root.innerHTML = table;
    });
}

如您所见,我们试图通过获取children元素来获取它们,但我们陷入困境,似乎找不到答案。

1 个答案:

答案 0 :(得分:2)

不确定children在这种情况下会解决什么,但是您可以通过查询直接进入路径:

[...svgDoc.querySelectorAll('path')].forEach(path => {
    path.addEventListener('click', e => {
        alert(path.id);
    })
})