首页 > 解决方案 > 在函数中传递附加参数时遇到问题

问题描述

我正在尝试在 d3 中编写一个函数,该函数将检查我的数据的“时间”并查看它是否在另外两个时间之间,并进行相应的过滤。

//start with a function to check if time for each data point is in between two other times
function timeInterval(data, start, end) {
    var time = data.Time

    if (start <= time <= end) {           
        return "inline";
    } else {
        return "none";
    };   
 }

//set the display of points to either inline or none
function updateTime(value) {
d3.selectAll(".events")
    .style("display", timeInterval("20:00", "24:00"));    
}


//When radio button on, call updateTime function
d3.selectAll("#timeFilterRadioButton").on("change", function() {
updateTime()
});

我的问题是我无法timeInterval使用 start 和 end 参数调用。调用timeInterval("20:00", "24:00")导致时间未定义。我可以成功传递数据的唯一方法是调用不带任何参数的函数:

 function updateTime(value) {
     d3.selectAll(".events")
        .style("display", timeInterval); //calling timeInterval in this manner, I'm able to console.log the time property of the data   
 }

很想知道我在这里哪里出错了。谢谢。

标签: javascriptjsonfunctiond3.js

解决方案


只需使用匿名函数来获取数据并将timeInterval函数包装在其中:

function updateTime(value) {
    d3.selectAll(".events")
        .style("display", function(d) {
            //your datum is here---^
            return timeInterval(d, "20:00", "24:00")
            //use it here-------^
        });
};

不相关,但这个:

if (start <= time <= end)

将归于true所有start <= time,不管end


推荐阅读