使用Button Counter更新Chart.js

时间:2015-07-16 15:20:24

标签: javascript jquery html css

我的网页上有以下代码行 - example/demo

HTML:

<div class="btn-area">
<button onclick="myfunction1()">Button 1</button>
<p id="btn1-output">0</p>
<button onclick="myfunction2()">Button 2</button>
<p id="btn2-output">0</p>
<button onclick="myfunction3()">Button 3</button>
<p id="btn3-output">0</p>
</div>

<div class="q11">
  <div class="question">
    <div id="canvas-holder" style="width: 250px; height: 250px; margin: 0 auto;">
      <canvas id="chart-area" width="250" height="250" />
    </div>
  </div>
</div>

CSS:

body {
  background: #1F253D;
  color: #FFF;
  padding: 20px;
}

button {
  background: #000;
  border: none;
}

.btn-area {
  float: left;
  width: 20%;
}

.btn-area button,
.btn-area p {
  display: inline;
}

.q11 {
  float: left;
  text-align: center;
  width: 50%;
}

JavaScript的:

var doughnutData = [{
  value: 1,
  color: "#E64C65",
  highlight: "#E64C65",
  label: "Button 1"
}, {
  value: 1,
  color: "#11A8AB",
  highlight: "#11A8AB",
  label: "Button 2"
}, {
  value: 1,
  color: "#FCB150",
  highlight: "#FCB150",
  label: "Button 3"
}];

window.onload = function() {
  var ctx = document.getElementById("chart-area").getContext("2d");
  window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {
    responsive: true
  });
};

var btn1Calls = 0;
var btn2Calls = 0;
var btn3Calls = 0;

function myfunction1() {
  btn1Calls++;
  document.getElementById('btn1-output').innerHTML = btn1Calls;
}

function myfunction2() {
  btn2Calls++;
  document.getElementById('btn2-output').innerHTML = btn2Calls;
}

function myfunction3() {
  btn3Calls++;
  document.getElementById('btn3-output').innerHTML = btn3Calls;
}

我目前正在使用this library在圆环形图表中显示信息。

如何才能使按钮上的计数器自动更新图表百分比,如果可能,请您使用分叉版本的演示提供示例?

1 个答案:

答案 0 :(得分:1)

如果您想要的话,可以查看此链接吗? 我更新了这样的函数:

function myfunction1() {
    btn1Calls++;
    document.getElementById('btn1-output').innerHTML = btn1Calls;
    doughnutData[0].value++;
    myDoughnut = new Chart(ctx).Doughnut(doughnutData, {
    responsive: true
});
}

function myfunction2() {
    btn2Calls++;
    document.getElementById('btn2-output').innerHTML = btn2Calls;
    doughnutData[1].value++;
    myDoughnut = new Chart(ctx).Doughnut(doughnutData, {
    responsive: true
});
}

function myfunction3() {
    btn3Calls++;
    document.getElementById('btn3-output').innerHTML = btn3Calls;
    doughnutData[2].value++;
    myDoughnut = new Chart(ctx).Doughnut(doughnutData, {
    responsive: true
});
}

http://codepen.io/anon/pen/BNPNeP