我正在嘗試制作一個網頁,當您單擊兩個按鈕時,它會更改背景顏色,但由于某種原因,除非我將它們從原始變數中更改,否則該事件不會發生。我認為這是因為我的函式由于某種原因沒有獲取和更改變數的值,但可能還有另一個我看不到的原因。是否有正確的方法來更改我不使用的函式內部的變數值?
let uno = false;
let dos = false;
function change1() {
uno = true;
return uno;
}
function change2() {
dos = true;
return dos;
}
if (uno && dos) {
document.body.classList.add("change");
}
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
background-color: #8AB0AB;
display: flex;
align-items: center;
justify-content: center;
}
.change {
background-color: #F4D35E;
}
<html>
<body>
<button id="1" onclick="change1()">
#1
</button>
<button id='2' onclick="change2()">
#2
</button>
</body>
</html>
uj5u.com熱心網友回復:
您只在頁面首次加載時檢查布爾變數一次,而不是在單擊更改變數值之后。
您需要if (uno && dos)在每次單擊其中一個按鈕后運行代碼,以更新 body 類。
函式中不需要return陳述句,因為onXXX()沒有使用函式的回傳值。
let uno = false;
let dos = false;
function change1() {
uno = true;
change_body();
}
function change2() {
dos = true;
change_body();
}
function change_body() {
if (uno && dos) {
document.body.classList.add("change");
}
}
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
background-color: #8AB0AB;
display: flex;
align-items: center;
justify-content: center;
}
.change {
background-color: #F4D35E;
}
<html>
<body>
<button id="1" onclick="change1()">
#1
</button>
<button id='2' onclick="change2()">
#2
</button>
</body>
</html>
uj5u.com熱心網友回復:
您需要在單擊按鈕后評估狀態。就像是:
var buttons = document.getElementsByTagName("button");
var isOn = true;
if(buttons){
for (var i = 0; i < buttons.length; i ) {
buttons[i].addEventListener("click", function (evt) {
this.classList.toggle("highlight");
evaluateButtons();
});
}
}
function evaluateButtons(){
isOn = true;
for (var i = 0; i < buttons.length; i ) {
if(!buttons[i].classList.contains("highlight")){
isOn = false;
}
}
if (isOn){
document.body.classList.add("modified");
} else {
document.body.classList.remove("modified");
}
}
.highlight{
background-color: green;
}
.modified{
background-color: gray;
}
<body>
<button>
#1
</button>
<button>
#2
</button>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519575.html
上一篇:這個函式大綱究竟如何用于鏈表?
下一篇:為什么我不能回圈這個函式?
