我正在尝试通过 Firebase Web API 为数据库引用设置一个值。当我在一个简单的 js 脚本中调用 set
函数时它起作用了。但是,当我尝试通过一个简单的按钮执行相同操作时,它并没有通过。
HTML 代码片段:
<html>
<head>
<meta charset="utf-8">
<title>Organiser</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase.js"></script>
<form>
<button id="sub"></button>
</form>
<script src="organiser_writer.js"></script>
</body>
</html>
JS 代码片段:
(function() {
// Initialize Firebase
console.log("Initialising Firebase");
var config = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(config);
firebase.database().ref().child('events').set("WORKS");
const buttonsub = document.getElementById('sub');
sub.onclick = function(){
console.log("before");
firebase.database().ref().child('events').set("DOESNT WORK");
console.log("after");
}
}());
将写入“WORKS”,但不会写入“DOESNT WORK”。
最佳答案
是否打印事件处理程序中的其他日志?在我看来他们不会,所以您的问题在于处理事件。
你使用了错误的变量名,看看这几行:
const buttonsub = document.getElementById('sub');
sub.onclick = function() {
应该是:
const buttonsub = document.getElementById('sub');
buttonsub.onclick = function() {
关于javascript - 按钮 onclick 回调中的 Firebase Web 引用为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50612792/