创建几个矩形后,每个矩形都有不同的id,我想获取它们的x属性。从SO的几个问题中,我发现我应该这样做:
d3.select('rect name1').attr('x')`
Run Code Online (Sandbox Code Playgroud)
但它返回:
未捕获的类型错误:无法读取 null 的属性“getAttribute”,
即使d3.select('rect name1')没有给出错误并返回st {_groups: Array(1), _parents: Array(1)}
var dataRectangle = [];
for (var i=0; i < 10 ; i++) {
dataRectangle.push(i);
}
var svg = d3.select('body').append('svg')
.attr('width', 1024)
.attr('height', 500);
var baseCircle = svg.selectAll('rect');
baseCircle = baseCircle.data(dataRectangle).enter().append('g');
baseCircle.append('rect')
.attr('width', 10)
.attr('height', 10)
.attr('x', 20)
.attr('y', 20)
.attr('fill', "none")
.attr("stroke-width", 4)
.style('stroke', "green")
.attr("id", function(d, i) { return 'name'+i; });
Run Code Online (Sandbox Code Playgroud)
首先,您必须使用#ID:
d3.select('rect #name1').attr('x')
Run Code Online (Sandbox Code Playgroud)
但这并不是唯一的问题。除此之外,这里还有一个错误的空格:
d3.select('rect #name1').attr('x')
//space here---^
Run Code Online (Sandbox Code Playgroud)
因此,您将选择具有给定 ID 的所有子元素<rect>。看看这里: https: //developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Combinators_and_multiple_selectors
显然,没有。你之前这么说...
d3.select('rect name1') 不会给出错误并返回 st {_groups: Array(1), _parents: Array(1)}
...但是,如果您查看该选择,您会发现它是一个空选择。我们来证明一下:
d3.select('rect #name1').attr('x')
Run Code Online (Sandbox Code Playgroud)
d3.select('rect #name1').attr('x')
//space here---^
Run Code Online (Sandbox Code Playgroud)
这解释了为什么你不能read property 'getAttribute' of null。
解决方案
它应该是:
d3.select('rect#name1').attr('x')
Run Code Online (Sandbox Code Playgroud)
或者,由于 ID 是唯一的,只需:
d3.select('#name1').attr('x')
Run Code Online (Sandbox Code Playgroud)
这是经过更改的代码:
var dataRectangle = [];
for (var i = 0; i < 10; i++) {
dataRectangle.push(i);
}
var svg = d3.select('body').append('svg')
.attr('width', 300)
.attr('height', 200);
var baseCircle = svg.selectAll('rect');
baseCircle = baseCircle.data(dataRectangle).enter().append('g');
baseCircle.append('rect')
.attr('width', 10)
.attr('height', 10)
.attr('x', 20)
.attr('y', 20)
.attr('fill', "none")
.attr("stroke-width", 4)
.style('stroke', "green")
.attr("id", function(d, i) {
return 'name' + i;
});
console.log("The size of the selection is: " + d3.select('rect name1').size())Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4497 次 |
| 最近记录: |