【问题标题】:SCRIPT438: Object doesn't support property or method 'attr'SCRIPT438:对象不支持属性或方法“attr”
【发布时间】:2020-01-28 12:25:17
【问题描述】:

以下代码导致错误..

这是用于创建垂直条形图的 D3 代码...下面提供的代码导致错误.. 它使用 SVG 并提供块 .. 但没有绘制垂直图表

//  the data that powers the bar chart, a simple array of numeric values
var chartdata = [40, 60, 80, 100, 70, 120, 100, 60, 70, 150, 120, 140];

//  the size of the overall svg element
var height = 200,
    width = 720,

//  the width of each bar and the offset between each bar
    barWidth = 40,
    barOffset = 20;


d3.select('#bar-chart').append('svg')
  .attr('width', width)
  .attr('height', height)
  .style('background', '#dff0d8')
  .selectAll('rect').data(chartdata)
  .enter().append('rect')
    .style({'fill': '#3c763d', 'stroke': '#d6e9c6', 'stroke-width': '5'})
    .attr('width', barWidth)
    .attr('height', function (data) {
        return data;
    })
    .attr('x', function (data, i) {
        return i * (barWidth + barOffset);
    })
    .attr('y', function (data) {
        return height - data;
    });
<!DOCTYPE HTML>
    <html>
    <head>
    <title>Vertical bar chart
    </title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>
        <h1>Vertical bar chart using D3</h1>
     <div id="bar-chart"></div>  
     </body>
     </html>

【问题讨论】:

标签: javascript html css d3.js


【解决方案1】:

按照d3-selectiond3.style()文档,只需将样式属性函数链调用移到末尾

返回具有指定名称的样式属性的值 指定的节点。如果节点具有指定的内联样式 名称,返回其值;否则,计算的属性值为 回来。另请参阅 selection.style。

所以.style() 不返回 D3 对象,因此您不能链接它。

这里是修复。

//  the data that powers the bar chart, a simple array of numeric values
var chartdata = [40, 60, 80, 100, 70, 120, 100, 60, 70, 150, 120, 140];

//  the size of the overall svg element
var height = 200,
    width = 720,

//  the width of each bar and the offset between each bar
    barWidth = 40,
    barOffset = 20;


d3.select('#bar-chart').append('svg')
  .attr('width', width)
  .attr('height', height)
  .style('background', '#dff0d8')
  .selectAll('rect').data(chartdata)
  .enter().append('rect')
    .attr('x', function (data, i) {
        return i * (barWidth + barOffset);
    })
    .attr('y', function (data) {
        return height - data;
    })
    .attr('width', barWidth)
    .attr('height', function (data) {
        return data;
    })
    .style({'fill': '#3c763d', 'stroke': '#d6e9c6', 'stroke-width': '5'})
    
<!DOCTYPE HTML>
    <html>
    <head>
    <title>Vertical bar chart
    </title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>
        <h1>Vertical bar chart using D3</h1>
     <div id="bar-chart"></div>  
     </body>
     </html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多