我正在尝试使用D3和jquery在svg图形中创建一个表。因此,我将三个文本元素附加到g元素,而不是调用函数来用几个tspan元素填充每个文本元素。 tspan元素的值来自json数组。
现在,当我加载页面时,只有第一个文本元素填充了值并正常显示。之后我得到一个错误,说:
TypeError:回调未定义
所以基本上这个函数似乎工作,我无法弄清楚接下来的两个文本元素的问题。我在这里监督什么?我必须这样做,不能使用像foreignobject这样的东西,因为它不受Internet Explorer的支持。
这是我的代码:
var data = [
{"month": "Jan", "tmp": 30, "pre": 50},
{"month": "Feb", "tmp": 25, "pre": 50},
{"month": "Mar", "tmp": 20, "pre": 50},
{"month": "Apr", "tmp": 16, "pre": 100},
{"month": "May", "tmp": 16, "pre": 200},
{"month": "Jun", "tmp": 16, "pre": 200},
{"month": "Jul", "tmp": 16, "pre": 300},
{"month": "Aug", "tmp": 16, "pre": 201},
{"month": "Sep", "tmp": 18, "pre": 100},
{"month": "Oct", "tmp": 20, "pre": 60},
{"month": "Nov", "tmp": 25, "pre": 50},
{"month": "Dec", "tmp": 32, "pre": 30},
]
function fillColumn (column) {
var col = chart.select("#" +column);
col.append('tspan')
.text("" +column);
for (i = 0; i < 12; i++){
var obj = data[i];
$.each(obj, function(j, val) {
if (j === column){
col.append('tspan')
.attr('x', table_x)
.attr('y', table_y + (table_height/13)*(i+1))
.text(val);
}
});
}
}
chart.append('g')
.attr('id', "table")
.attr('x', table_x)
.attr('y', table_y)
.attr('width', table_width)
.attr('height', table_height)
.append('text')
.attr('id', "month")
.attr('x', table_x)
.attr('y', table_y)
.attr('text-anchor', 'middle')
.call(fillColumn("month"));
chart.select('#table')
.append('text')
.attr('id', "tmp")
.attr('x', table_x + table_width/3)
.attr('y', table_y)
.attr('text-anchor', 'middle')
.call(fillColumn("tmp"));
chart.select('#table')
.append('text')
.attr('id', "pre")
.attr('x', table_x + table_width*2/3)
.attr('y', table_y)
.attr('text-anchor', 'middle')
.call(fillColumn("pre"));
答案 0 :(得分:2)
first argument到.call
是一个函数 - 您正在调用函数,然后将返回值传递给.call
。
您需要的是:
.call(fillColumn, "month");
您的fillColumn
定义变为:
function fillColumn(col, column) {
col.append('tspan')
.text("" + column);
请注意,我没有看到重新选择任何内容,因为fillColumn的第一个参数将是您text
选择的call
。
顺便说一句,这里你真的不需要jquery
,基本的JavaScript就足够了:
for (key in obj){
if (key === column){
col.append('tspan')
.attr('x', table_x)
.attr('y', table_y + (table_height / 13) * (i + 1))
.text(obj[key]);
}
}