简体   繁体   English

谷歌图表饼图事件

[英]Google Charts Pie Chart Event

I have the following code to generate several pie charts on my page:我有以下代码可以在我的页面上生成几个饼图:

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

As you can see, when I click on a slice it will print the text of that slice.如您所见,当我单击切片时,它将打印该切片的文本。 What I need is to set an ID on the table and fetch that ID inside of the event (where I have alert(this.getSelection().focusNode.data) ).我需要的是在表上设置一个 ID 并在事件内部获取该 ID(我有alert(this.getSelection().focusNode.data) )。

I could certainly include the id in the outer div like:我当然可以将 id 包含在外部 div 中,例如:

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

Now I just need to figure out how to get to that data in the alert.现在我只需要弄清楚如何在警报中获取该数据。

to prevent the value for question from becoming locked to the last value inside the event listener,防止question的值被锁定到事件侦听器中的最后一个值,
assign the event within a closure (function)在闭包(函数)中分配事件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM