0

我正在使用 HTML 和 JavaScript(通过 Glitch)以及 Firebase 创建一个简单的投票网站,我按照教程进行操作。我一切正常,投票工作正常,并按预期显示结果。我现在想要获取结果并使用它们在我的 HTML 页面上显示图表。我了解这是如何工作的,而不是如何将投票结果变量放入图表的 JS 代码中。我正在使用charts.js,其代码位于底部。y 值应该是读取总票数的变量,但它不起作用。有什么建议么?

谢谢


var myStates = [];
var myTimes = [];

// Variables to hold the count for each state
var TrumpCount = 0;
var BidenCount = 0;

// Define database connection to correct child branch, MyTemperature
var myDBConn = firebase.database().ref("USvote");

// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
  TrumpCount = 0;
  BidenCount = 0;

  // The data returned from the branch is put into a variable, dataPoint
  var dataPoint = data.val();

  // Populate the lists with the various data from the database
  myStates.push(dataPoint.USvote);
  myTimes.push(dataPoint.Time);

  // add 1 to the appropriate counter
  for (i = 0; i < myStates.length; i++) {
    if (myStates[i] == "Trump") {
      TrumpCount = TrumpCount + 1;
    }
    if (myStates[i] == "Biden") {
      BidenCount = BidenCount + 1;
    }
  }

  // Update the page elements with the results of each count
  document.getElementById("TrumpCount").innerHTML = TrumpCount;
  document.getElementById("BidenCount").innerHTML = BidenCount;
});


// JS code for using charts
JSC.Chart("chartDiv", {
  type: "column",
  series: [
    {
      points: [{ x: "Biden", y: BidenCount}, { x: "Trump", y: TrumpCount}]
    }
  ]
});
4

1 回答 1

0

仅在 firebase 已加载并执行所需操作时才尝试放置 chart.js 代码。

尝试这个:

var myStates = [];
var myTimes = [];

// Variables to hold the count for each state
var TrumpCount = 0;
var BidenCount = 0;

// Define database connection to correct child branch, MyTemperature
var myDBConn = firebase.database().ref("USvote");

// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
  TrumpCount = 0;
  BidenCount = 0;

  // The data returned from the branch is put into a variable, dataPoint
  var dataPoint = data.val();

  // Populate the lists with the various data from the database
  myStates.push(dataPoint.USvote);
  myTimes.push(dataPoint.Time);

  // add 1 to the appropriate counter
  for (i = 0; i < myStates.length; i++) {
    if (myStates[i] == "Trump") {
      TrumpCount = TrumpCount + 1;
    }
    if (myStates[i] == "Biden") {
      BidenCount = BidenCount + 1;
    }
  }

  // Update the page elements with the results of each count
  document.getElementById("TrumpCount").innerHTML = TrumpCount;
  document.getElementById("BidenCount").innerHTML = BidenCount;
  
  
// JS code for using charts
JSC.Chart("chartDiv", {
  type: "column",
  series: [
    {
      points: [{ x: "Biden", y: BidenCount}, { x: "Trump", y: TrumpCount}]
    }
  ]
});
});
于 2020-10-13T12:19:17.003 回答