Javascript 获取现有SVG元素的属性,并使用d3.js作为数据绑定
我有一个现有的svg元素,例如:Javascript 获取现有SVG元素的属性,并使用d3.js作为数据绑定,javascript,d3.js,svg,Javascript,D3.js,Svg,我有一个现有的svg元素,例如: <svg width="300" height="200"> <circle cx="50" cy="10" r="5" fill="green"></circle> <circle cx="100" cy="20" r="10" fill="green"></circle> <circle cx="150" cy="30" r="15" fill="green">&
<svg width="300" height="200">
<circle cx="50" cy="10" r="5" fill="green"></circle>
<circle cx="100" cy="20" r="10" fill="green"></circle>
<circle cx="150" cy="30" r="15" fill="green"></circle>
</svg>
但是,我不知道如何将所有cx值收集到一个数组中,并将它们连接到圆中。(或者,在没有数据数组的情况下,有一种更直接的方法来实现这一点。)
解释如何在控制台中查看所有属性,但没有解释如何存储它们或将它们绑定到DOM元素。这对您有用吗
d3.selectAll('circle').datum(function() {
return parseFloat(this.getAttribute('cx'));
});
是的,很好。沿着这些思路,这也是可行的:
d3.selectAll('circle').datum(function(){return+d3.select(this.attr('cx'))})代码>但这不是:d3.selectAll('circle').datum(()=>{+d3.select(this.attr('cx'))
fwiw@jtr13不能将this
与箭头函数一起使用。它应该是:d3.selectAll('circle').datum((d,i,n)=>{+d3.select(n[i]).attr('cx')代码>啊哈。这个
是被淘汰还是被认为是不好的形式?不是。这只是常规函数和箭头函数的基本区别。请阅读以下文件:
d3.selectAll('circle').datum(function() {
return parseFloat(this.getAttribute('cx'));
});