[英]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.