javascript - 如何使用 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>
解决方案
var div = document.getElementById('moisture');
div.innerHTML = 'Moisture: 55%';
<div id='moisture'></div>
推荐阅读
- gradle - 如何使用 Gradle 创建项目结构?
- sql - 为该特定用户授予选择权限后,视图中没有结果 - 默认用户看到结果
- c# - C# SQL Command .Fill 在 Firebird 服务器上调用时耗时过长,使用存储过程加入表
- javascript - TinyMCE 工具栏未显示
- c++ - 如何更改在 C++ 中使用 boost 库创建的共享内存的路径
- java - orientdb 3.0 列表中的 WHERE 子句
- jquery - 为什么 JQuery 中的“replaceWith”函数没有完全替换数据?
- python - 如何在基于类的视图中获取当前插件对象的实例
- python - pytables 的写入速度比 h5py 快得多。为什么?
- wso2 - WSO2 IS API 获取服务提供商的用户声明