我试图实现一个逻辑,每次单击按钮时,计数在1和0之间交替。在下面的代码中,计数始终为0,因为每次按下按钮时,函数将计数设置为0.请帮助我出去并提前感谢
<html>
<head>
<script type="text/javascript">
function main(){
var button = document.getElementById('button');
count = 0;
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
答案 0 :(得分:3)
在全局范围内声明count
变量。
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
答案 1 :(得分:2)
在全局范围内声明按钮。并使用按位运算符在0和1之间切换,就像这样..
<script type="text/javascript">
var count = 0; //global scope
function main(){
var button = document.getElementById('button');
if(button.onclick){
alert(count);
count ^= 1; //bitwise operator
}
}
</script>
答案 2 :(得分:1)
每次单击按钮时,都会调用main()。每次调用main()时,都要将计数设置为0才能启动。将计数放在功能范围之外。
答案 3 :(得分:1)
我同意Ataur的答案,但你可能想考虑将这个用例作为最佳实践的bool。
<html>
<head>
<script type="text/javascript">
var buttonIsOn = true;
function main(){
var button = document.getElementById('button');
if(button.onclick && buttonIsOn){
alert("turning button off");
buttonIsOn = false;
}
else { // no need to check again if using bool
alert("turning button on");
buttonIsOn = true;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
答案 4 :(得分:1)
您应该在该功能之外将计数设置为0。
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
答案 5 :(得分:1)
您需要使用按钮挂钩点击事件,并在0和0之间交替。 1点击。
function main() {
var button = document.getElementById('button');
var count = 0;
button.addEventListener("click", function() {
if (count == 0) {
alert(count);
count = 1;
}
else if (count == 1) {
alert(count);
count = 0;
}
});
}
进一步确保main
处于document
状态时调用ready
函数或将main
函数调用放在body
标记结束的正上方。像这样的东西
<body>
<button type="button" id="button" >Click Me!</button>
<script>
main();
</script>
</body>