D3 - Uncaught TypeError:无法读取未定义的属性“length” [英] D3 - Uncaught TypeError: Cannot read property 'length' of undefined

查看:319
本文介绍了D3 - Uncaught TypeError:无法读取未定义的属性“length”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码中出现错误。其余字段的数据没有问题。

Error in code below. There is no issue with the data of the remaining fields.

<!DOCTYPE html>
<html>
<head>
<title>Data Entry</title>
<meta charset='utf-8'/>
<meta name="keywords" content="D3"/>
<script type="text/javascript" src="d3/d3.v3.js"></script>
<style type="text/css">
.table {border: 2px; text-align: center;}
.th {font-size: 12px; font-weight: bold; color: blue;}
.td {font-size: 12px;}
</style>
</head>
<body>
<script type="text/javascript">
var dataset;
d3.text('data.txt', function(d){dataset = d3.csv.parse(d, function(d){return {id: +d.id, name: d.name};});});
d3.select('body').append('table').attr('class','table').selectAll('tr').data(dataset).enter().append('tr');
</script>
</body>
</html>

屏幕截图如下:

推荐答案

您需要考虑两件事,将您对回调函数之外的数据集的引用。因此,虽然您已将数据集变量创建为全局变量,以便可以在 d3.text 块在生成表时没有时间填充。因此,如果你将你的表生成代码移动到 d3.text 块,你会解决这个问题。您还可以使用 queue.js 对数据请求进行排队。

There are two things you need to consider, the first is that you've put the reference to dataset outside of your call back function. So while you've created the dataset variable as a global so that it can be accessed outside of the d3.text block it hasn't had time to be populated when the table is generated. So if you move your table generation code into the d3.text block you'll address this issue. You can also queue your data requests using queue.js.

另一件事是,你试图绑定一个对象的单个元素数组,你需要一个对象数组d3迭代数组来创建,在这个case,表行。然后使用对象中的信息填充表。

The other thing was that you were trying to bind a single element array of objects, where you need an array of objects as d3 iterates over the array to create, in this case, table rows. The information in the objects is then used to populate your table.

这两个问题都在下面的代码中解决,但是,请注意,我没有填充表单元格的任何东西,只是创建了行。为此,我建议您阅读 d3noobs post
和引用的stackoverflow回答 Shawn Allen

Both of these issues are addressed in the following code, however, note that I haven't populated the tables cells with any thing, just created the rows. To do that I'd suggest reading d3noobs post and the referenced stackoverflow answer by Shawn Allen.

var dataset =[];
d3.text('data.txt', function(d) {
    d3.csv.parse(d, function(d) {
        var el = {
            id: +d.id,
            name: d.name
        };
        dataset.push(el)
    });
var table = d3.select('body')
    .append('table')
    .attr('class', 'table');

table.selectAll('tr')
    .data(dataset).enter()
    .append('tr')
    .attr("class", "rows");

});

最后一件事是你可以使用 d3.csv 而不是 d3.text d3.csv.parse

One final thing is that you could just use d3.csv instead of d3.text and d3.csv.parse.

这篇关于D3 - Uncaught TypeError:无法读取未定义的属性“length”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆