简体   繁体   English

无法在 javascript 中用 onclick function 更改变量值

[英]Unable to change variable value with onclick function in javascript

I am trying to change the boolean value from true to false and false to true whenever the button is clicked however the value is changing within the function but when I console the value outside the function it is giving the default value that I set during the variable declaration`每当单击按钮时,我都试图将 boolean 的值从 true 更改为 false,将 false 更改为 true 但是值在 function 内发生变化但是当我控制 function 之外的值时,它给出了我在变量期间设置的默认值声明`

var bool = 0; 
switchCameraButton.addEventListener('click', function() {
                
                camera.switch();
                if(bool == 0){
                    bool = 1;
                }else{
                    bool = 0;
                }
                console.log(bool);
            });

console.log(bool);

` `

I was trying to change the boolean value when ever the button is clicked but the value is not changing i mean it is changing within the onclick function but not outside the function我试图在单击按钮时更改 boolean 值,但该值没有改变我的意思是它在 onclick function 内发生变化,但不在 function 之外

you can use this script to change the value of a variable on click event您可以使用此脚本更改单击事件中变量的值

 var bool_val=false; function changeVal(){ bool_val=;bool_val. console;log(bool_val); }
 <input type="button" value="change" onclick="changeVal();">

a possible solution is using localStorage to save your bool value here is an example一个可能的解决方案是使用 localStorage 来保存你的 bool 值这里是一个例子

// Your boolean is whatever you have in the localStorage if the localStorage is empty the default value will be 0
let bool = localStorage.getItem('myBoolValue') | 0; 

switchCameraButton.addEventListener('click', function() {             
    camera.switch();
    
    // this is the logical not operator it transform your bool variable from 0 to 1 and vise versa
    bool = !bool;
    
    // save your bool in localStorage, by using the + am just turning true or false to 1 or 0
    localStorage.setItem('myBoolValue', +bool);
 });

console.log(bool);

I think you need to make sure that the bool variable is declared outside the onclick function. This way, the value of bool will be accessible outside the function, and will be updated when button is clicked.我认为您需要确保 bool 变量在 onclick function 之外声明。这样,bool 的值将在 function 之外访问,并在单击按钮时更新。

For example:例如:

var bool = 0;

switchCameraButton.addEventListener('click', function() {
    camera.switch();
    if(bool == 0){
        bool = 1;
    }else{
        bool = 0;
    }
});

console.log(bool);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM