javascript d3.js foreach 在 svg 中包含的所有路径上循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14531671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
d3.js foreach loop on all the paths contained in a svg
提问by fabien
I have a svg generated by d3.js like this one:
我有一个由 d3.js 生成的 svg,如下所示:
<svg height="1094" width="1254">
<g id="countries" stroke-width="1px" transform="">
<path d="M100,519.150,200,250" fill="rgba(100,100,100,0.8)"
stroke="rgba(200,200,200,0.5)" id="id1" class="1"></path>
<path d="M100,519.150,200,250" fill="rgba(100,100,100,0.8)"
stroke="rgba(200,200,200,0.5)" id="id2" class="1"></path>
<path d="M100,519.150,200,250" fill="rgba(100,100,100,0.8)"
stroke="rgba(200,200,200,0.5)" id="id3" class="3"></path>
<path d="M100,519.150,200,250" fill="rgba(100,100,100,0.8)"
stroke="rgba(200,200,200,0.5)" id="id4" class="1"></path>
</g>
</svg>
I want to do somtehing like that :
我想做这样的事情:
foreach(path in #countries){
if(this.class === 3){dostuff}
}
I've tried the jquery way :
我试过 jquery 的方式:
$('#countries').find('path').each(function( index ) {
console.log(this);
});
... log nothing
... 什么都不记录
I've tried the d3.js way (countries was initialized as follow : countries = svg.append('svg:g').attr('id', 'countries')):
我已经尝试过 d3.js 方式(国家初始化如下:) countries = svg.append('svg:g').attr('id', 'countries'):
countries.select('path').each(console.log(this));
countries.selectAll('path').each(console.log(this));
log the window object (wtf?)
记录窗口对象(wtf?)
回答by nautat
The method selection.eachrequires a function as argument:
方法selection.each需要一个函数作为参数:
countries.selectAll('path').each(function(d,i) { console.log(this); });

