在d3中获取元素的属性并不优雅
Getting the properties of an element in d3 is not elegant
这是我的代码片段:
我试图了解如何使用d3获取DOM对象的属性。在这种情况下,在对象返回事件之后。例如,我将如何访问"x1"属性。
var svg = d3.select('svg')
.append('polyline')
.attr('x1', 20)
.attr('y1', 100)
.attr('x2', 100)
.attr('y2', 100)
.attr('points', "20,100 100,100 100,100 180,100")
.attr('fill', 'none')
.attr('stroke', palette.gray)
.attr('marker-start', "url(#triangle)")
.attr('marker-mid', "url(#triangle)")
.attr('marker-end', "url(#triangle)")
.on('click', function(){
console.log('polyline click');
console.log(this);
});
我使用
- console.log(this['x1']);--返回"未定义"
- console.log(this.attr('x1');--TypeError:this.attr不是函数
- console.log(this.property('attr');--TypeError:this.properties不是函数
我最终发现解决方案是使用:d3.select(this).attr("cx")
什么是"this"?如果我将"this"打印到控制台,我似乎会将DOM对象作为返回
<polyline x1="20" y1="100" x2="100" y2="100" points="20,100 100,100 100,100 180,100" fill="none" stroke="#708284" marker-start="url(#triangle)" marker-mid="url(#triangle)" marker-end="url(#triangle)">
不得不再次选择元素似乎有点"不明智"。我错过了一个技巧吗?
this
确实是您所记录的DOM元素,问题是attr()
是D3函数,特别是在D3.selection上
您需要做的是将DOM元素转换为一个选择,这样您就可以利用d3-helper函数。这样做的方法就像你有一样
d3.select(this)
相关文章:
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- Css order属性不't在Jquery设置时更新
- Bookshelf.js设置的属性不在数据库中
- 查找数组's按属性不存在于另一个数组中的对象
- 在javascript函数调用中传递的HTML属性不完整
- 在jQuery中链接时CSS属性不起作用
- 设置AngularJS控制器属性不能是使用Coffeescript的最后一行
- 向插件添加属性(不是默认方式)
- Css 属性不会更改(javascript)
- 函数中的 angularJS 访问对象属性不起作用
- JavaScript - 对象属性不一致
- 控制器的属性不会动态更改
- Express和Typescript-Error.stack和Error.status属性不存在
- 使用 css() 更改自定义属性不起作用
- 自定义CSS复选框jQuery诱导的“;“已检查”;属性不't在视觉上”;“检查”;复选框
- 在d3中获取元素的属性并不优雅
- 具有多个依赖项的Ember属性不会按预期更新
- 对象属性不是在工厂成员函数内部创建的
- 调用类属性不起作用
- 为什么onclick属性不起作用