Javascript - 新手脚本不起作用



有人可以解释为什么这个脚本不起作用吗?我试图弄清楚很长时间,但我没有设法做到。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <script>
        function Xyz() {
            var x = 0;
        }
        function Switch() {
            if (x == 0) {
                document.body.style.backgroundColor = "black";
                x = 1;
            }
            else {
                document.body.style.backgroundColor = "white";
                x = 0;
            }
        }
    </script>
</head>
<body>
    <button type="button" onclick="Switch()">Click me</button>
</body>
</html>

if(x==0)

由于x不存在,因此它会在此处抛出 ReferenceError 并中止函数的其余部分。

您需要先声明x


这:

function Xyz()
{
 var x=0;
}
  • 创建函数的局部变量x,并且
  • 反正从不叫

您需要定义变量 x。在这个例子中,我使用了吊装。

<!DOCTYPE html>
<html>
<head>
<script>
function Xyz()
{
 var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
  var x;
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html>

问题是您需要在使用变量之前声明一个变量。

function Switch()
{
if(x==0) // this x is not defined. 
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}

由于您需要使用相同的变量在每次单击时更新它,因此请在函数外部定义它。

<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function Xyz()
{
 var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html> 

最新更新