2012-09-18 34 views
3

如何檢查JavaScript或jQuery中的svg對象的類型? 我想檢查標籤是否爲SVGAnimatedStringjQuery:檢查SVG元素的類型

當我輸出的對象到控制檯它輸出以下內容:

console.log(this.href); 
SVGAnimatedString // is an object and can be expanded 

在我的代碼我嘗試檢查它是否是一個SVG對象,但檢查不能正常工作。

if (this.href == 'SVGAnimatedString'){ //this check does not work 
    //it s an svg object 
    var url = this.href.animVal 
} 
else{ 
    var url = this.href; //get the href from the <a> element 
} 

如何正確檢查它是否是SVGAnimatedString對象?

回答

3

您不應該使用==來比較類型。您需要使用instanceof。你可以這樣做:

if (this.href instanceof SVGAnimatedString){ //this check works!!! 
    //it s an svg object 
    var url = this.href.animVal 
} 
else{ 
    var url = this.href; //get the href from the <a> element 
} 

SVGAnimatedString有較少的瀏覽器支持。記住這一點。 :)

+1

感謝它現在的作品。關於瀏覽器兼容性:我只想檢查類型,因爲SVGAnimatedString對象是從我用D3創建的svg對象返回的。我使用Chrome和FF對其進行了測試,並且工作正常。你認爲我會遇到使用其他瀏覽器的問題嗎? –

+0

這應該工作,你可能也可以使用'if('animVal'in this.href)'' –