gpt4 book ai didi

javascript - 尝试制作一个开/关/自动按钮

转载 作者:行者123 更新时间:2023-11-28 20:15:49 24 4
gpt4 key购买 nike

我是 javascript 新手,正在尝试制作一个每次单击都会循环打开/关闭/自动的按钮。每个状态还必须运行 if 语句中的代码和 switch 中的代码。我目前无法让它正常运行。稍后,一旦我开始工作,我希望“if 语句”函数位于其自己的 .js 文件中,以便我可以在其他开/关/自动按钮中引用它。而开关将是主代码的一部分。我做错了什么?

function cycle()
{
var onoffB = ();
if (document.getElementById("button1").value="On")
{
onoffB=1;
document.getElementById("button1").value="Off";
}

else if (document.getElementById("button1").value="Off")
{
onoffB=2;
document.getElementById("button1").value="Auto"
}
else
{
onoffB=0;
document.getElementById("button1").value="On"
}

switch(onoffB)
{
case 0:
//running code;
break;
case 1:
//running code;
break;
case 2:
//running code;
break;
}
}

</script>
</head>
<body>

<input type="button" id="button1" value="On" onclick="cycle()">

</body>
</html>

最佳答案

嗯,我立刻就发现了两个大问题。首先,以下语法是无效的 JavaScript:

var onoffB = ();

我认为你的意思是 onoffB 有一个未定义的状态,你最好这样做:

var onoffB = null;

其次,您使用的是赋值 (=),而不是比较(=====)。 (根据经验,您应该始终更喜欢 === 而不是 ==,除非您有充分的理由并且知道自己在做什么。)请考虑以下内容:

var x = 3;                        // *sets* the value of x to 3

var x == 3; // invalid syntax
var x === 3; // invalid syntax

if( x = 2 ) { print 'x is 2'; } // will *always* print 'x is 2', no matter what
// the value of x is; x now has the value 2
// PROBABLY NOT WHAT YOU WANT

if( x = 0 ) { print 'x is 0'; } // will *never* print 'x is 0', no matter what
// the value of x is; x now has the value 0
// PROBABLY NOT WHAT YOU WANT

if( x === 5 ) { print 'x is 5'; } // will only print 'x is 5' if the value of x
// is 5; value of x

if( x === 0 ) { print 'x is 0'; } // will only print 'x is 0' if the value of x
// is 0; value of x unchanged

我也会对此做出很多风格上的改变。由于您的格式选择,您的代码确实很难阅读。此外,还有很多不必要的重复代码。如果我写这篇文章,我会将其缩短为以下内容:

switch( document.getElementById("button1").value ) {
case 'On':
// do stuff
break;
case 'Off':
// do stuff
break;
case 'Auto':
// do stuff
break;
default:
// probably an error condition; show message, maybe?
break;
}

如果您确实需要开/关/自动按钮的值,可以将其设置在case主体内。

关于javascript - 尝试制作一个开/关/自动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com