简体   繁体   English

如何从每个获取“ id”属性 <g> 用JavaScript在嵌套的svg中标记?

[英]How to get the “id” attribute from each <g> tag in a nested svg with javascript?

I am newbie with javascript and dealing with svg files, but I would like to get the 'id' attribute from each <g> tag in a nested svg through a javascript function depending on which g element is clicked. 我是javascript新手,正在处理svg文件,但是我想通过javascript函数从嵌套svg中的每个<g>标记中获取'id'属性,具体取决于单击的g元素。 According to my example I want to get: 根据我的示例,我想得到:
MyGroup1 MyGroup1的
MyGroup2 MyGroup2
And how could I save the result as string variable? 以及如何将结果另存为字符串变量?

Please,I would appreciate if someone could show me how to get this, as I've searched and tried everything I know to try. 拜托,如果有人可以告诉我如何获得此信息,我将不胜感激,因为我已经搜索并尝试了所有我想尝试的东西。

 <html> <script type="text/javascript"> function(){ //What javascript code should be here? } </script> <body> <svg width="200" height="200" style="background-color: #D2B48C; display: block; margin-bottom: 5px;" id="embeddedSVG"> <g id="myGroup1 onclick="function();" fill="blue" style="font-size: 18px; text-anchor: middle; font-family: serif;"> <circle id="myCircle" cx="100" cy="75" r="50" stroke="firebrick" stroke-width="3" /> <text x="100" y="155">Hello World</text> <text x="100" y="175">From Embedded SVG!</text> </g> <g id="MyGroup2" onclick="funciont();"> <rect x="30" y="40" width="180" height="30" fill="#ddd" stroke="black" /> <text x="50" y="63" font-size="18pt" fill="black"> Display Msg</text> </g> </svg> </body> </html> 

You can pass this as a parameter to the function. 您可以this作为参数传递给函数。

 function showId(g) { var str = g.id; console.log(str); } 
 #embeddedSVG { background-color: #D2B48C; display: block; margin-bottom: 5px; } #myGroup1 { font-size: 18px; text-anchor: middle; font-family: serif; } 
 <svg width="200" height="200" id="embeddedSVG"> <g id="myGroup1" onclick="showId(this)" fill="blue"> <circle id="myCircle" cx="100" cy="75" r="50" stroke="firebrick" stroke-width="3" /> <text x="100" y="155">Hello World</text> <text x="100" y="175">From Embedded SVG!</text> </g> <g id="MyGroup2" onclick="showId(this)"> <rect x="30" y="40" width="180" height="30" fill="#ddd" stroke="black" /> <text x="50" y="63" font-size="18pt" fill="black">Display Msg</text> </g> </svg> 

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

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