首页 > 解决方案 > SCRIPT438:对象不支持属性或方法“attr”

问题描述

以下代码导致错误..

这是创建垂直条形图的 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>

标签: javascripthtmlcssd3.js

解决方案


根据d3-selection d3.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>


推荐阅读