在javascript中为嵌入SVG的元素添加点击事件
我从维基百科得到了这个SVG图片。 http://upload.wikimedia.org/wikipedia/commons/e/e8/ BlankMap-World6-Equirectangular.svg
我使用以下代码将其嵌入到网站中:
I got this SVG image from Wikipedia. http://upload.wikimedia.org/wikipedia/commons/e/e8/BlankMap-World6-Equirectangular.svg I embedded it into a website using this code:
<embed src="circle1.svg" type="image/svg+xml" />
如果运行此操作,您可以检查元素并查看源代码
所有国家在图像中是单独的元素
如果我点击一个国家,我想提醒该国的id(每个国家都有一个两个字母的id在SVG。
有人知道一种方法
If you run this, you can inspect the element and see the source code All countries in the image are seperate elements If I click on a country, I want to alert the id of that country (every country has got an id of two letters in the SVG. Does anyone know a way to do this? Would it be easier if I place it into a element?
好的使用你的意见我发现了一个答案给我问题,我在svg本身添加了这个代码。
Okay using your comments I found an answer to my problem. I added this code in the svg itself.
<script type="text/javascript"> <![CDATA[
function addClickEvents() {
var countries = document.getElementById('svg1926').childNodes;
var i;
for (i=0;i<countries.length;i++){
countries[i].addEventListener('click', showCountry);
}
}
function showCountry(e) {
var node = e.target;
if (node.id != 'ocean') {
node = getCorrectNode(node);
}
alert(node.id);
}
function getCorrectNode(node) {
if (node.id.length == 2 || node.id == 'lakes') {
return node;
}
return getCorrectNode(node.parentNode);
}
]]> </script>
函数addClickEvents在svg加载时触发。
但是我还有另一个问题。我必须使用
The function addClickEvents is triggered when the svg loads. But I still have another problem with this. I have to embed this svg (with the code) into a HTML document using
<embed src="circle1.svg" type="image/svg+xml" />
而不是警告id,我必须将其放入HTML文档中的div。
如何从svg获取此ID?
Instead of alerting the id, I have to place it into a div in the HTML document. How do I get this id from the svg?