所以我有这个 SVG
我成功连接了一个 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
在该上下文中解析为什么,但您可以通过查询直接访问路径:
[...svgDoc.querySelectorAll('path')].forEach(path => {
path.addEventListener('click', e => {
alert(path.id);
})
})
关于javascript - 从SVG中的路径获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55053154/