必须单击两次以提交Firebase更新JS查询

时间:2019-10-28 18:33:13

标签: javascript html firebase firebase-realtime-database

我已经创建了一个Web应用程序,并且要使其正常运行,我必须使用开关。我使用复选框和一些CSS创建了开关。 我已经在实时数据库中添加了一个值,并希望根据开关的状态将其更改为1和0。但是我的问题是,我必须单击两次开关才能提交数据库中的值更新。

  1. 第一次单击时,开关变为绿色(表示其值设置为1),但db中的值不变
  2. 第二次单击时,开关不会更改颜色并保持绿色,现在db中的值已成功更新为1。
  3. 第三次单击时,开关的状态已关闭,但db中的值仍为1
  4. 第四次单击时,开关的颜色没有改变,现在db中的值已成功更新为0

Javascript:


                    var database = firebase.database();

                    var ref1 = database.ref("switches/S1");
                    ref1.on("value", getData1);
                    function getData1(data) {
                        var checkbox = document.getElementById("switch");
                        checkbox.value = data.val();
                        ischecked=checkbox.checked;

                        if (checkbox.value == 1) {
                            checkbox.checked = true;
                            }
                        else if (checkbox.value == 0) {
                            checkbox.checked = false;
                            }
                    //this funciton is just to check the value of the field in the db
                        }
                    function toggle1(){ 
                        var ischecked = document.getElementById("switch").checked;

                        if(ischecked===true){
                            //set db value to 0 if clicked when switch is on
                            database.ref("switches").update({'S1': 0});
                        }

                        else{
                            //set db value to 1 if clicked when switch is off
                            database.ref("switches").update({'S1': 1});
                        }
                        } 

HTML:

<span><h2>FAN</h2></span>
<label class="switch">
<input type="checkbox" id="switch" onclick="toggle1()">
<span class="slider round"></span>

我希望它具有响应性和可靠性。谢谢。

0 个答案:

没有答案