【问题标题】:D3: call() not working for appended text element (Type error)D3:call() 不适用于附加的文本元素(类型错误)
【发布时间】:2015-12-02 02:57:42
【问题描述】:

我正在尝试使用 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"));

【问题讨论】:

  • 这个错误到底是从哪里来的?

标签: javascript jquery d3.js svg callback


【解决方案1】:

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]);
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2015-06-21
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多