首页 > 解决方案 > 下载点击计数器 + 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();
    });
}

我怎么解决这个问题?

标签: javascripthtmlfirebase-realtime-database

解决方案


您需要确保先读取该值,然后再将其设置为新值。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(),这确保了这两种情况都自动发生。


推荐阅读