如何获取svg元素类型

use*_*621 4 javascript svg d3.js

我有一个问题,我怎么能得到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);

         }
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用,有人可以帮忙,谢谢!


***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); 
         }
Run Code Online (Sandbox Code Playgroud)

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

Sir*_*rko 5

只需使用该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;
      }

    });
Run Code Online (Sandbox Code Playgroud)

编辑

d3js' select()不会返回元素本身,而是返回一个d3js包装器(非常类似于jQuery,例如).所以最简单的方法是使用该call()方法将函数应用于所有匹配(在这种情况下select()只有一个).