d3.select('rect id')。attr('y')返回无法读取null的属性'getAttribute'

时间:2018-01-07 21:01:59

标签: d3.js

在创建了几个具有不同id的矩形之后,我想获得他们的x属性。关于SO的几个问题,我发现我应该这样做:

d3.select('rect name1').attr('x')` 

但它返回:

  

未捕获的TypeError:无法读取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; });

2 个答案:

答案 0 :(得分:4)

首先,您必须使用#作为ID:

d3.select('rect #name1').attr('x')

但这不是唯一的问题。除此之外,这里还有一个错误的空间:

d3.select('rect #name1').attr('x')
//space here---^

因此,您选择具有<rect> 儿童的给定ID的所有元素。看看这里: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)}

...但是,如果您查看该选项,您会看到它是选项。让我们证明一下:

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())
<script src="https://d3js.org/d3.v4.min.js"></script>

这就解释了为什么你不能read property 'getAttribute' of null

解决方案

应该是:

d3.select('rect#name1').attr('x')

或者,由于ID 唯一,只需:

d3.select('#name1').attr('x')

以下是您更改的代码:

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(d3.select('rect#name1').attr("x"))
<script src="https://d3js.org/d3.v4.min.js"></script>

答案 1 :(得分:-1)

如果您的html文件中没有标签,也会显示此错误。例如。您正在呼叫d3.select("svg"),但html文件中没有定义svg元素。