我有一个很大的svg文件,该文件显示在html页面上,其中包含以下代码
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
version="1.0"
width="680"
height="520"
viewBox="1754 161 9938 7945"
id="svg2">
<title
id="title4">Countries of Europe</title>
<desc
id="desc6"> A blank Map of Europe. Every country has an id which is its ISO-3166-1-ALPHA2 code in lower case.
Members of the EU have a class="eu", countries in europe (which I found turkey to be but russia not) have a class="europe".
Certain countries are further subdivided the United Kingdom has gb-gbn for Great Britain and gb-nir for Northern Ireland. Russia is divided into ru-kgd for the Kaliningrad Oblast and ru-main for the Main body of Russia. There is the additional grouping #xb for the "British Islands" (the UK with its Crown Dependencies - Jersey, Guernsey and the Isle of Man)
... file continues on
我已将此JavaScript代码用于svg代码的不同部分,并使用此代码针对其ID
document.querySelector('svg').addEventListener('click',function(e){
const dir = (e.target.closest('g').id);
alert(dir);
});
但是我得到这个错误:
Uncaught TypeError: Cannot read property 'addEventListener' of null
at Object.<anonymous> (index.js:29)
at __webpack_require__ (bootstrap f06ab605832628ed0f5f:19)
at Object.<anonymous> (html5-entities.js:190)
at __webpack_require__ (bootstrap f06ab605832628ed0f5f:19)
at bootstrap f06ab605832628ed0f5f:62
at bootstrap f06ab605832628ed0f5f:62
每当我单击大部分零件时,它将返回另一个错误:
(index):27 Uncaught TypeError: Cannot read property 'addEventListener' of null
但工程图的很少部分会提示该元素的ID