javascript - 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>
解决方案
根据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>
推荐阅读
- java - 每次按下按钮时导致我的应用程序崩溃的原因是什么?
- docker - 如何修复 ModuleNotFoundError:没有名为“rest_auth”的模块
- c# - 是否可以部署自包含的 .NET Framework 应用程序?
- csh - 如果:使用小于号时的数字格式错误
- bash - 如何将十进制/浮点格式输出写入文件?
- python - 如何修改此代码以提高其检测眼睛注视/瞳孔的稳定性?在光线不足的情况下,此代码的性能非常糟糕
- tensorflow - 使用 Tensorflow Hub 模块作为自定义 tf.Estimator 的基础时出现 tf.Estimator.predict() 问题
- ruby-on-rails - Heroku buliid 在 Bundler 版本上失败,无论安装哪个
- regex - 仅在 sed 或 awk 匹配后替换空格
- c++ - C++ / SFML:使用两个递归调用将凸形打印到屏幕上仅显示第一个递归调用的形状,而不是第二个