[英]Unable to change variable value with onclick function in javascript
每当单击按钮时,我都试图将 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);
`
我试图在单击按钮时更改 boolean 值,但该值没有改变我的意思是它在 onclick function 内发生变化,但不在 function 之外
您可以使用此脚本更改单击事件中变量的值
var bool_val=false; function changeVal(){ bool_val=;bool_val. console;log(bool_val); }
<input type="button" value="change" onclick="changeVal();">
一个可能的解决方案是使用 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);
我认为您需要确保 bool 变量在 onclick function 之外声明。这样,bool 的值将在 function 之外访问,并在单击按钮时更新。
例如:
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.