javascript - 如何使用 javascript 从嵌套 svg 中的每个 <g> 标记获取 "id"属性?

标签 javascript svg

我是 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/

相关文章:

html - 是否可以将外部 SVG 填充加载到 inline-svg 元素中?

javascript - 如何在刷新整个页面后清除下拉列表框。使用 ASP.NET MVC

javascript - 如何在表单验证时在 Angular 模板中显示 <span> 元素?

javascript - svg 圆圈不是用 javascript 绘制的

javascript - dom 中的属性但在 jQuery 选择器中不可用

javascript - SVG 鼠标事件在 Firefox4 中有效,但在 IE8 中无效

html - 设置div动态填充其余高度?

javascript - 如何在拖放区添加默认图像?

javascript - 类型错误 : Value does not implement interface EventListener

javascript - 从 Object.freeze 获取随机对象