我的按钮没有改变功能



我想知道为什么按钮没有变为另一个功能,第二次点击按钮时按钮会变成红色。

我的目标是有一个按钮,它将根据你是否按下一次来改变功能

<!DOCTYPE html>
<html>
<head>
<style>
#hello {
padding: 30px 60px;
background-color: #4db8ff;
width: 100px;
text-align: center;
margin-left: auto;
margin-right: auto;
cursor: pointer;
color: white;
font-family: arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="hello" onclick="button()">START</div>
</body>
<script>
var x = true;
if(x == true) {
function button() {
x = false;
alert("once");
}
}

if(x == false) {
function button() {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}
</script>
</html>

在页面加载时,您有条件地创建两个可能的函数定义之一。第二个定义不会取代第一个定义,因为您在某个时刻重新分配了布尔标志。

创建一个在内部检查x状态的函数:

function button() {
if(x) { // Comparing against true is redundant
x = false;
alert("once");
} else {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}

您的函数button()只定义了一次。不能基于条件定义函数,它将在执行其周围的代码后立即定义。因此,您需要将if语句放在函数中。

<!DOCTYPE html>
<html>
<head>
<style>
#hello {
padding: 30px 60px;
background-color: #4db8ff;
width: 100px;
text-align: center;
margin-left: auto;
margin-right: auto;
cursor: pointer;
color: white;
font-family: arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="hello" onclick="button()">START</div>
</body>
<script>
var x = true;
function button(){
if(x) {
x = false;
alert("once");
} else {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}
</script>
</html>

最新更新