我是 javascript 新手,正在处理 svg 文件,但我想从每个 <g>
中获取“id”属性通过 javascript 函数在嵌套 svg 中标记,具体取决于单击哪个 g 元素。根据我的例子我想得到:
我的组 1
我的组2
以及如何将结果保存为字符串变量?
拜托,如果有人能告诉我如何得到这个,我将不胜感激,因为我已经搜索并尝试了我所知道的一切尝试。
<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>
最佳答案
您可以将 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>
关于javascript - 如何使用 javascript 从嵌套 svg 中的每个 <g> 标记获取 "id"属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38806816/