[英]d3: Why does this function not remove elements?
Working in d3, I've got a function call that correctly draws a bar chart, but it doesn't update it correctly. 在d3中工作,我有一个函数调用可以正确绘制条形图,但不能正确更新它。 Here's the important part of my code:
这是我的代码的重要部分:
# Drawing Elements
@svg = d3.select(@s).append('svg').attr('width',@w).attr('height',@h)
@rects = @svg.selectAll('rect')
@labels = @svg.selectAll('text')
drawRects: (data) ->
rects = @rects.data(data)
rects.enter().append('rect')
rects.exit().remove()
rects.attr('x', (d,i) => this.xScale(i) )
.attr('y', (d) => @h - this.yScale(d) )
.attr('width', @w / @data.length - @pad)
.attr('height', (d) => this.yScale(d) )
.attr('fill','#FFC05C')
drawLabels: (data) ->
labels = @labels.data(data)
labels.enter().append('text')
labels.exit().remove()
labels.text( (d) -> d )
.attr('text-anchor','middle')
.attr('x', (d,i) => this.xScale(i) + ((@w / @data.length - @pad)/2) )
.attr('y', (d) => @h - this.yScale(d) + 15 )
.attr('fill','white')
update: (data) ->
this.drawRects(data)
this.drawLabels(data)
When I initially set the graph I create some data (in this case an array of 20 numbers) and call the draw methods: 最初设置图形时,我会创建一些数据(在这种情况下为20个数字组成的数组)并调用draw方法:
data = [1..20]
this.drawRects(data)
this.drawLabels(data)
The graphs are drawn correctly. 图形绘制正确。
However, if these methods are called a second time, to update the data, the new data is placed in the DOM, but the old data is left behind as well, so it's just making a whole new set of elements. 但是,如果第二次调用这些方法以更新数据,则新数据将放置在DOM中,但旧数据也将被保留,因此它只是构成了一组全新的元素。
What am I doing wrong here that's keeping .exit()
from removing the old DOM elements? 我在做什么错,这是在阻止
.exit()
删除旧的DOM元素的问题?
You need to reselect the rect
and text
elements and assign them the new data: 您需要重新选择
rect
和text
元素并为其分配新数据:
drawRects: (data) ->
rects = @svg.selectAll('rect').data(data)
#...
drawLabels: (data) ->
labels = @svg.selectAll('text').data(data)
#...
In your code you always assign the new data to the old (empty) @rect
and (empty) @labels
collections. 在代码中,您总是将新数据分配给旧的(空)
@rect
和(空) @labels
集合。 And the data will be treated as "entered" for these empty collections and thus new elements will be created and nothing will be removed. 对于这些空集合,数据将被视为“输入”,因此将创建新元素,并且不会删除任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.