javascript - 下载点击计数器 + Firebase 数据库
问题描述
我的代码保存了该值,当页面刷新并单击按钮时,该值将返回到 1
var button = document.getElementById("button-download"),
count = 0;
button.onclick = function() {
count += 1;
firebase.database().ref('counter').set(count);
updateValue();
};
function updateValue() {
firebase.database().ref('counter').once('value', function(snapshot) {
var badge = document.getElementById("badge-value");
badge.innerHTML = "Download: " + snapshot.val();
});
}
我怎么解决这个问题?
解决方案
您需要确保先读取该值,然后再将其设置为新值。Firebase 现在有一个内置的增量运算符来做到这一点:
button.onclick = function() {
firebase.database().ref('counter').set(firebase.database.ServerValue.increment(1));
};
firebase.database().ref('counter').on('value', function(snapshot) {
var badge = document.getElementById("badge-value");
badge.innerHTML = "Download: " + snapshot.val();
});
你会注意到我不再更新(也不需要)本地也不再count
刷新 UI 。onclick
那是因为代码现在用 监听数据库on()
,这确保了这两种情况都自动发生。
推荐阅读
- excel - VBA Word - 快速提取 Excel 文件
- python - How to stop g-mail marking my e-mails as dangerous?
- javascript - javascript:为什么我需要单击两次才能更改显示属性?
- php - PDO prepare with unknown OR statements
- javascript - 如何创建与 express 或 http 反应的服务器?
- android-source - Stop SE Linux from Enforcing on Android AOSP
- java - How to take the values from the variable and enter in the text box?
- java - how to index each feature elasticsearch featurecollection
- python - 通过对具有数字和字符串变量的数据框进行分组来转置
- excel - VBA Excel String concatenation upper than max length, How to?