简体   繁体   中英

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`

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

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

// 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.

For example:

var bool = 0;

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

console.log(bool);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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