繁体   English   中英

调用JavaScript函数时出错 - “找不到变量”

[英]Error when calling JavaScript function — “can't find variable”

我正在尝试使用JavaScript圣经完成和练习,并且无法让我的脚本运行。

该任务是创建一个页面,允许用户查询行星的名称,并通过与行星名称匹配的脚本及其存储在关联数组中的数据,调用其距离和直径信息。

我试图通过一个按钮调用函数'getPlanetInfo'(onclick ='getPlanetInfo()')。 但是,当我尝试运行它时,我的错误控制台报告它找不到名为'getPlanetInfo'的变量。

我在下面附上了我的JS和HTML代码。 任何想法为什么我的功能没有被正确调用将非常感激。

HTML:

<!DOCTYPE html>
<html>
<head>
    ...
    <script type="text/javascript" src="planets.js"></script>
</head>
<body>
        <h1>Check a planet's distance from the sun and its diameter!</h1>
        <form>
            <input type="text" name="entry" id="entry">
            <input type="button" value="Check it!" onClick="getPlanetInfo()">
        </form>
</body>
</html>

JS:

var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";

var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";

var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";

function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
    if (planetNames[i] == selectedPlanet)
    {
        break;
    }
}

if (i < planetNames.length)
{
    alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}

else
{
    alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}

这一行:

alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")

planetDistances[i]之后缺少一个+号,所以该函数有一个语法错误而且没有创建,当然在调用时找不到它。

http://www.jsfiddle.net帮助您创建一个我们都可以看到的可重现的案例,在您需要提出问题时使用它。

你错过了一个+ - 这个:

alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")

应该

alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")

在加载脚本时,您应该使用Firebug之类的东西来捕获语法错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM