无法更改d3.js矩形的填充

pra*_*432 2 javascript coffeescript d3.js

所以我有这个代码 -

bars.
  append('rect')
  .attr('x', 0)
  .attr('y', (d, i) ->
    return yScale(i)
  ).attr('width', (datum) ->
    return xScale(datum.freq)
  )
  .attr('height', barHeight)
  .attr('fill', 'blue')
  .attr('class', 'bar')
  .on('click', ->
    bars.selectAll('rect').attr('fill', '#0000ff')
    currentFill = d3.select(this).style('fill')
    nextColor = {}
    if currentFill == '#0000ff'
      nextColor = '#ff0000'
    else
      nextColor = '#0000ff'
    d3.select(this).style('fill', nextColor)
  )
Run Code Online (Sandbox Code Playgroud)

但是,bars.selectAll('rect')不会改变矩形的颜色.为什么?

Jon*_*nah 5

替换attr()style().你的线路:

bars.selectAll('rect').attr('fill', '#0000ff')
Run Code Online (Sandbox Code Playgroud)

应该:

bars.selectAll('rect').style('fill', '#0000ff')
Run Code Online (Sandbox Code Playgroud)