如何获取svg元素类型

how to get svg element type

本文关键字:svg 元素 类型 获取 何获取      更新时间:2023-09-26

我有一个问题,我如何获得svg元素的类型,顺便说一句,我使用d3.js

我有类似这个的东西

var selectedElement = svg.select("." + STYLE.selected);
         if (selectedElement instanceof SVGCircleElement){
            alert("here circle");
            selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
         }
           if (selectedElement instanceof SVGPathElement){
             alert("here path");
                appendMarkerm(selectedElement,false);
         }

但是它似乎不起作用,有人能在这里帮忙吗,谢谢!!


***finally, i made it work like this*** 
var selectedElement = svg.select("." + STYLE.selected);
           if (selectedElement.node() instanceof SVGCircleElement){
            selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
         }
           if (selectedElement.node() instanceof SVGPathElement){
            changeMarkerStyle(selectedElement,false); 
         }

cauz-selection.node()将返回选择的第一个元素

只需使用tagName属性:

svg.select("." + STYLE.selected)
   .call( function(){
      switch( selectedElement.tagName.toLowerCase() ) {
        case 'circle': 
          alert("here circle");
          this.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
          break;
        case 'path':
          alert("here path");
          appendMarkerm( this, false );
          break;
      }
    });

编辑

d3js的select()不返回元素本身,而是为其返回一个d3js包装器(非常像jQuery)。因此,最简单的方法是使用call()方法将函数应用于所有匹配(在只有select()的情况下,这只是一个)。