我的代码中有两个不同的d3.svg.area()变量,其中每个变量基本上都可以正常工作(元素按我期望的那样绘制在SVG上)。

现在,我想更改代码以便根据条件选择两种方法之一-它根本不起作用,屏幕上未显示任何内容,但控制台也未记录任何错误。

我的代码如下所示:

    var lineFunction = d3.svg.area()
        .x(function (d) {return d.x;})
        .y(function (d) {return d.y;})
        .y0(function (d) {return (d.y+ 10) ;})
        .y1(function (d) {return (d.y- 10) ;})
        .interpolate("basis");

    var otherFunction = d3.svg.area()
        ....//analogue to above one


    d3arrows.enter()
            .append("path")
            .attr("d", function (d){
                if(condition == 1) {lineFunction}
                else {otherFunction}
             ;})
             //.attr("d", lineFunction ) <--like this it works!
            .attr("stroke", "blue")
            .attr("stroke-width",  2)
            .attr("fill",  "yellow");


我也尝试使用return lineFunctionreturn otherFunction,但这会导致d3库本身出现“属性错误的无效值”。

if语句的结构应该正确,它取自StackOverflow中以前帖子的答案。但是他们都没有使用路径数据生成器,所以也许这就是我的代码的问题。

我在这里做错了什么?

最佳答案

基本上有两个错误:


您在回调中缺少return
您没有将参数传递给行生成器函数。


解决这个问题的一种方法可能是这样的:

d3arrows.enter()
        .append("path")
        .attr("d", function (d) {
            if (condition == 1) {
                return lineFunction(d);
            } else {
                return otherFunction(d);
            }
        })

10-04 23:03