Google Charts饼图活动

时间:2017-10-23 20:00:32

标签: javascript charts google-visualization

我有以下代码在我的页面上生成几个饼图:

for(var question in questions){
    console.log(question);
    var curChart = $('<div class="summary-chart"></div>');
    curChart.appendTo(contentDiv);
    var data = [["answer_text", "quantity"]];
    for(var answer in questions[question]){
        data.push([answer, questions[question][answer]]);
    }
    var data = google.visualization.arrayToDataTable(data);
    chart = new google.visualization.PieChart(curChart[0]);
    google.visualization.events.addListener(chart, 'select', function(){
        alert(this.getSelection().focusNode.data); //alert slice text
    });
    chart.draw(data, {title: question, pieHole: 0.3, pieSlieceText: 'percentage', backgroundColor: '#efefef'});
}

如您所见,当我点击切片时,它将打印该切片的文本。我需要的是在表上设置一个ID并在事件中获取该ID(我有alert(this.getSelection().focusNode.data))。

我当然可以在外部div中包含id,如:

var curChart = $('<div class="summary-chart" data-id="'+question+'"'></div>');

现在我只需要弄清楚如何在警报中获取该数据。

1 个答案:

答案 0 :(得分:1)

以防止question的值被锁定到事件侦听器内的最后一个值,
在闭包(函数)中分配事件

for(var question in questions) {
    if (questions.hasOwnProperty(question)) {
        drawQuestion(question);
    }
}

function drawQuestion(question) {
    var curChart = $('<div class="summary-chart"></div>');
    curChart.appendTo(contentDiv);
    var data = [["answer_text", "quantity"]];
    for(var answer in questions[question]){
        data.push([answer, questions[question][answer]]);
    }
    var data = google.visualization.arrayToDataTable(data);
    chart = new google.visualization.PieChart(curChart[0]);
    google.visualization.events.addListener(chart, 'select', function(){
        console.log(question, this.getSelection().focusNode.data);
    });
    chart.draw(data, {title: question, pieHole: 0.3, pieSlieceText: 'percentage', backgroundColor: '#efefef'});
}