调用JavaScript函数时出错--“;可以't查找变量“;
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帮助你创建一个我们都能看到的可复制的案例,当你需要问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的东西来捕捉语法错误。
相关文章:
- Javascript 变量使用 jquery 查找变量
- "可以't查找变量:cordova”;
- "可以't查找变量:window“;在suds.js中
- ReferenceError:Can't查找变量:functionName
- 在 for 循环中查找变量的迭代总和
- 按名称查找变量
- ReferenceError:Can't在AngularJS中查找变量:xxxService,Karma
- JQuery可以't从单独的javascript文件中查找变量
- 代码在shell中运行,但提供'可以't查找变量'从文件运行时出错
- 防止函数在外部作用域中查找变量
- 下划线模板:按名称查找变量
- 正则表达式用于在文本字符串中查找变量名称及其值
- 查找变量中是否存在选择器
- 可以't查找变量:FB
- 异常本机EvalAndFetch:ReferenceError:Can't查找变量:cordova
- Chutzpah-can't查找变量:module
- 在AngularJS应用程序中包含CryptoJS-Can't查找变量:CryptoJS
- ReferenceError:Can't在Safari中查找变量:ValidatorEnable
- 如何在jquery中的特定字符串中查找变量的值
- 调用JavaScript函数时出错--“;可以't查找变量“;