首页 > 解决方案 > 如何使用 JS 更新网站上显示的单个值?

问题描述

在实时 firebase 数据库和一些 arduino 代码的帮助下,我在我的网站上显示了盆栽土壤的水分含量。但是,当更新 firebase 数据(每 0.3 秒)时,它不会同时更新网站上的单个值,而是在每次更新时添加一个新行/打印。片刻之后,我的网站现在看起来像这样:

Moisture: 661Moisture: 658Moisture: 660Moisture: 658Moisture: 657,并且每次更新都会在其后添加 Moisture: xxx。我想要发生的只是让它显示一次,然后推送数据以更新第一个值,而不是添加一个新值。

我将在下面留下我的代码,我该怎么做呢?很难在互联网上找到有关此的内容,因为我不确定我在寻找什么(JS 新手)。

代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/styles.css">
    
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
  
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "xx",
    authDomain: "xx",
    databaseURL: "xx",
    projectId: "xx",
    storageBucket: "xx",
    messagingSenderId: "xx",
    appId: "xx"
      };
      firebase.initializeApp(config);
    </script>
    

  <script>
    
    var database = firebase.database();

    
    var ref = firebase.database().ref("plant-patrol/Moisture");
    ref.once("value")
    .then(function(snapshot) {
    var key = snapshot.key; // "plant-patrol"
    var childKey = snapshot.child().key; // "Moisture"
  
    });
  </script>
    
<script>
    var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
   console.log(snapshot.val());
    var snapshotJSON = JSON.stringify(snapshot.val());
    var moisture = snapshotJSON;
    moisture = moisture.replace(/[{""}]/g, '');
    moisture = moisture.replace(/[:]/g, ': ');
    document.write(moisture);

  
}, function (error) {
   console.log("Error: " + error.code);
});
    </script>  
  

    
    <script src="/script.js" defer></script>
  </head>
</html>

标签: javascripthtmlfirebase-realtime-database

解决方案


var div = document.getElementById('moisture');
div.innerHTML = 'Moisture: 55%';
<div id='moisture'></div>


推荐阅读