我有一些javacript,我正试图在HTML页面上实现它。代码如下-如何让它在.html文件打开后立即运行?它希望我一打开它就提示我输入权重。
<script type="text/javascript">
var weight = parseInt(prompt("What is your weight?"));
if (weight > 126) {
alert('Please enter a weight lighter than 126');
}
document.writeln('<br/>');
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function recruit() {
if (0 < weight < 112){
document.writeln('You are in' + wArray[0] +'class!');
}
if (112 < weight < 115){
alert('You are in' + wArray[1] +'class!');
}
if (weight > 115 && weight < 118){
alert('You are in' + wArray[2] +'class!');
}
if(weight > 118 && weight < 122){
alert('You are in' + wArray[3] +'class!');
}
if (weight > 122&& weight < 126){
alert('Your weight class is' + wArray[4]);
}
</script>发布于 2011-12-06 06:43:06
脚本有两个问题:
recruit()缺少右括号}recruit() recruit() anywhere。其他几个问题:):
112 < weight < 115不是你想要的。即使当权重为1000时,它也会返回true。它将检查权重是否大于112,然后比较结果是否小于115。尝试:
var weight = 1000;
// 112 < 1000 => true, true < 115 => true
if (112 < weight < 115) {
alert("112 < weight < 115");
}if中的weight < 118和另一个if中的weight > 118,那么如果权重恰好为118会发生什么?if { } else if { }块而不是多个if-s。在recruit函数中,即使权重是110并且执行了第一个if块的主体,您仍然会检查输出字符串中每隔一个if.'You are in ' + wArray[0] + ' class!:)。正如火箭在注释中所写的那样:10作为第二个参数(基数)来调用parseInt(),以强制解析为十进制。请尽快查看this.document.writeln,因为它正在教你糟糕的实践。例如,请参见this或this.就是解决这些问题的一个版本。
注意:代码在window.onload中执行,以确保文档的其余部分已经加载,这样他就可以访问div了。
发布于 2011-12-06 06:38:09
<script type="text/javascript">
var weight = parseInt(prompt("What is your weight?"));
if (weight > 126) {
alert('Please enter a weight lighter than 126');
}
document.writeln('<br/>');
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function recruit() {
if (0 < weight < 112){
document.writeln('You are in' + wArray[0] +'class!');
}
if (112 < weight < 115){
alert('You are in' + wArray[1] +'class!');
}
if (weight > 115 && weight < 118) {
alert('You are in' + wArray[2] +'class!');
}
if(weight > 118 && weight < 122){
alert('You are in' + wArray[3] +'class!');
}
if (weight > 122&& weight < 126){
alert('Your weight class is' + wArray[4]);
}
}
recruit();
</script>发布于 2011-12-06 06:39:49
它似乎工作得很好:http://jsfiddle.net/maniator/XRGHt/
您在末尾遗漏了一个}。
https://stackoverflow.com/questions/8392849
复制相似问题