我正在处理一个SVG文件,我想知道有多少多边形有某个类(比方说" .red")
这是简单的javascript循环:
var polygons = document.getElementsByTagName("polygon");
var j = 0;
for (i = 0; i < polygons.length; i++) {
if (polygons[i].className == "red") {
j++;
}
};
alert("There are " + j + " red shapes")
和小提琴: https://jsfiddle.net/tuj0rmnx
我无法获得预期的结果。 返回0而不是3 ... 无法弄清楚为什么...... 我想必须有一个DOM问题或某些问题,但不能正确...
我读过这个:How to access SVG elements with Javascript 但我不想创建一个活动。我想在最后实现的就是打印&#34;结果使用document.write()方法自动在页面中...
任何帮助表示赞赏!!
答案 0 :(得分:2)
您可以首先选择具有正确类别的元素:
var polygons = document.querySelectorAll("polygon.red");
alert("There are " + polygons.length + " red shapes")
另一种方法是使用classList
:
var polygons = document.getElementsByTagName("polygon");
var j = 0;
for (i = 0; i < polygons.length; i++) {
console.log( polygons[i].className );
if (polygons[i].classList.contains( "red" ) ) {
j++;
}
};
alert("There are " + j + " red shapes")
您的代码失败,因为className
没有返回字符串,而是SVGAnimatedString
,显然不等于您的"red"
。
答案 1 :(得分:0)
SVG中的属性通常具有与HTML中同名属性不同的定义。
属性className
的类型不是字符串。因此,您无法将其与"red"
之类的字符串常量进行比较。它不会工作。
SVG中属性className
的类型为AnimatedString
。 AnimatedString
有两个属性:
baseVal
,其中包含属性的初始值,animVal
,其中包含该属性的当前值。如果属性当前正在设置动画,则可能与baseVal不同。因此,要使代码生效,您需要将类测试更改为:
if (polygons[i].className.baseVal == "red") {
请参阅下面的演示:
var polygons = document.getElementsByTagName("polygon");
var j = 0;
for (i = 0; i < polygons.length; i++) {
if (polygons[i].className.baseVal == "red") {
j++;
}
};
alert("There are " + j + " red shapes")
&#13;
.shapes {
fill: #b9b9b9;
fill-opacity: 1;
stroke: white;
stroke-opacity: 1;
stroke-width: 0.002;
}
.red {
fill: red
}
&#13;
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="433" height="378" preserveAspectRatio="none" version="1.1" x="0" y="0">
<g class="shapes">
<polygon points="35.582,121.756 0.578,61.128 35.582,0.5 105.588,0.5
140.592,61.128 105.588,121.756 " />
<polygon points="181.334,121.756 146.331,61.128 181.334,0.5 251.341,0.5
286.345,61.128 251.341,121.756 " />
<polygon class="red" points="327.087,121.756 292.083,61.128 327.087,0.5 397.094,0.5
432.098,61.128 397.094,121.756 " />
<polygon points="35.582,377.071 0.578,316.443 35.582,255.815
105.588,255.815 140.592,316.443 105.588,377.071 " />
<polygon class="red" points="181.334,377.071 146.331,316.443 181.334,255.815
251.341,255.815 286.345,316.443 251.341,377.071 " />
<polygon points="327.087,377.071 292.083,316.443 327.087,255.815
397.094,255.815 432.098,316.443 397.094,377.071 " />
<polygon points="111.328,249.413 76.324,188.785 111.328,128.157
181.334,128.157 216.338,188.785 181.334,249.413 " />
<polygon class="red" points="257.081,249.413 222.077,188.785 257.081,128.157
327.087,128.157 362.091,188.785 327.087,249.413 " />
</g>
</svg>
&#13;