调用JavaScript函数时出错--“;可以't查找变量“;

Error when calling JavaScript function — "can't find variable"

本文关键字:查找 变量 可以 JavaScript 出错 调用 函数      更新时间:2023-09-26

我正试图从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帮助你创建一个我们都能看到的可复制的案例,当你需要问js问题时使用它。

您缺少一个+-这个:

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的东西来捕捉语法错误。