我正在尝试制作一个显示在我的页面控制台中的点击计数器。相关代码如下:
var database = firebase.database();
database.ref().on("value", function(snapshot) {
console.log("Logging snapshot.val " + snapshot.val());
console.log("Logging hits " + snapshot.val().hits);
var hitCounter = snapshot.val().hits;
console.log("hitCounter is " + hitCounter)
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
//so I can get it to display the value in the database, but not to increase. WTF
function showStuff() {
$("#content").fadeIn("slow");
hitCounter++;
console.log("hitCounter in showstuff() function is = " + hitCounter);
//this console log above doesn't even fire. WTF!?
//Ask on stack overflow some other time
database.ref().set({
hits: hitCounter
});
}正如注释所示,我可以让数据库中的数字显示,但不能增加。甚至showStuff()中的console.log也不会触发(但是淡入会触发)。到底怎么回事?
发布于 2018-12-12 07:44:21
您正在使用的事件回调将在每次更改数据时向其传递快照。如果需要使用showStuff函数显示该值,则必须在回调函数中调用该函数
database.ref().on("value", function(snapshot) {
console.log("Logging snapshot.val " + snapshot.val());
console.log("Logging hits " + snapshot.val().hits);
var hitCounter = snapshot.val().hits;
console.log("hitCounter is " + hitCounter);
showStuff();
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});https://stackoverflow.com/questions/53733780
复制相似问题