我是否正确调用了我的JavaScript函数?

时间:2014-05-28 09:38:11

标签: javascript function

我是Javascript的新手。

我正在制作我的第一个冒险游戏。

我使用onClick测试了以下代码,它运行良好:

// JavaScript Document
function changeColour() 
{
    if (document.getElementById('colourTest').style.backgroundColor='yellow') 
    {
        document.getElementById('colourTest').style.backgroundColor='red';
    }
    else
    {
        document.getElementByID('colourTest').style.backgroundColor='yellow';
    }
}

var direction;

direction = prompt("Which direction would you like to go ?");

if ( direction == "North" )
{
    changeColour();
}
else
{
    console.log("You can't go in that direction ?");    
}

这是HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>

<body>
    <div id="colourTest">
    </div>
</body>
</html>

当用户输入单词North时,我希望黄色div变成红色,否则,用户被告知他们不能朝那个方向前进。

我确信这是某种语法错误:D

嗨,这是一个更新:

HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script  type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<script  type="text/javascript" ></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">

</head>

<body onload="load();">

        <img id="myimg" alt="My Image" src="images/image1.jpg" />
        <form>
            <input name="heading" type="text" id="which" value="" />    
        </form>

</body>
</html>

这是JS:

   // JavaScript Document

        var img = new Image();
        img.src = "images/image1.jpg";



function whichImage(b)
{
    var image = document.getElementById("myimg");

    if (b == "North")
    {
        image.src = "images/image2.jpg";
    }
    else
    {
        image.src = "images/image1.jpg";
    }
}

function whichDirection (x) 
{
    if (x == "North" || x == "South" || x == "East" || x == "West" ) 
    {
        document.write("You choose to go " + direction);
    }
    else
    {
        document.write("You can't go in that direction");
    }
}

function load()
{
    var direction = document.getElementById('which').value;

    whichDirection(direction);
    whichImage(direction);


}

我不明白为什么当用户输入单词North时,用户的输入方向不允许图像更改为image2.jpg。

JS实际上可以从html中捕获文本输入,然后将其与函数中的变量一起使用吗?

此外,在这个版本中,DOM似乎没有加载,因为没有图像可供查看。

1 个答案:

答案 0 :(得分:0)

我立即看到的两个错误(可能还有更多)是......

if (document.getElementById('colourTest').style.backgroundColor='yellow')

分配而不是比较。使用==进行比较(与其他地方一样)。和...

document.getElementByID('colourTest').style.backgroundColor='yellow';

JavaScript区分大小写。函数名称应为getElementById(与其他地方一样)。


在这种情况下,存在逻辑错误和语法错误。通过在浏览器的调试工具中查看JavaScript控制台,通常可以注意到后者。如果它试图执行该行代码,那么您会在那里看到错误。另一方面,逻辑错误可能更难以精确定位。对于那些您希望在浏览器的调试工具中熟悉调试器的人。

您可以点击特定的JavaScript代码行来设置&#34;断点&#34;代码执行暂停的地方。暂停后,您可以检查变量的运行时值,逐行逐步执行以检查其行为等。这就是验证代码是否按预期执行的方式。

相关问题