简体   繁体   中英

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) ).

I could certainly include the id in the outer div like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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