D3中的排序条形图不起作用

时间:2015-03-02 06:26:47

标签: javascript d3.js

我在D3中创建了一个条形图,显示了选择的单选按钮条形图,我想按升序或降序排序。当点击按钮时它没有排序,所以我不知道什么是错的,但任何帮助将不胜感激:

http://jsfiddle.net/m4s5m5je/2/ [添加排序前]

在我按下排序按钮后,条形图也不会显示和排序按钮:

http://jsfiddle.net/m4s5m5je/3/

var sort_btn = document.getElementById('sort')
sort_btn.on("click", function(){
    var self = d3.select(this);
    var ascending = function(a,b){
            return a.value - b.value;
    };
    var descending = function(a,b){
            return b.value - a.value;
    }
    var state = +self.attr("state");
    var txt = "Sort data: ";
    if(state === 0){
            data.sort(ascending);
            state = 1;
            txt += "descending";
    } else if(state === 1){
            data.sort(descending);
            state = 0;
            txt += "ascending";
    }
    self.attr("state", state);
    self.html(txt);

1 个答案:

答案 0 :(得分:0)

您错过了结束括号});

并将sort_btn实现移出plot.call

为了进行分类工作,您应该修复更多地方。

updated fiddle

plot.call(chart, {
          data: data,
          axis:{
            x: xAxis,
            y: yAxis
          },
          gridlines: yGridlines
        }); 
var sort_btn = document.getElementById('sort')
sort_btn.on("click", function(){
var self = d3.select(this);
var ascending = function(a,b){
        return a.value - b.value;
};
var descending = function(a,b){
        return b.value - a.value;
}
var state = +self.attr("state");
var txt = "Sort data: ";
if(state === 0){
        data.sort(ascending);
        state = 1;
        txt += "descending";
} else if(state === 1){
        data.sort(descending);
        state = 0;
        txt += "ascending";
}
self.attr("state", state);
self.html(txt);

});