JavaScript 中的变量与 firebase

Variable in JavaScript with firebase

我正在使用 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}]
    }
  ]
});

尝试仅在 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}]
    }
  ]
});
});