我为学生们制作了一个互动数学页面。下面的这个小程序在我的电脑上工作正常但在上传到教师网页时无法在线工作。 你能帮我找到原因吗? 谢谢
<script>
function Triarea() {
var base, height, area;
base = document.getElementById('base').value;
height = document.getElementById('height').value;
area = document.getElementById('area').value;
if (area === 1 / 2 * base * height) {
document.getElementById('results').innerHTML = area + " <h2>CORRECT</h2>";
} else {
document.getElementById('results').innerHTML = area + " <h2> WRONG try again </h2>";
}
}
</script>
<h2>Base:</h2> <input type="text" size="25" style="font-size:20pt" id="base" value=""></br>
<h2>Height:</h2> <input type="text" size="25" style="font-size:20pt" id="height" value="">
<br/>
<span id="results"><h2>Enter your answer in the Area box below then click on calculate</h2></span>
</br>
<h1>Area:</h1> <input type="text" size="25" style="font-size:20pt" id="area"> </br>
<input type="button" size="100" style="background-color: red; color:yellow;height:80px;width:140px;font-size:30px; " value="Calculate" onClick="Triarea()"><br>
答案 0 :(得分:0)
我没有改变任何逻辑,只是将脚本放在头部。您可能将脚本放在错误的位置?
您可以尝试使用以下内容:
来自JSFiddle:jsFiddle Link
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
Triarea = function() {
var base, height, area;
base = document.getElementById('base').value;
height = document.getElementById('height').value;
area = document.getElementById('area').value;
if (area === 1 / 2 * base * height) {
document.getElementById('results').innerHTML = area + " <h2>CORRECT</h2>";
} else {
document.getElementById('results').innerHTML = area + " <h2> WRONG try again </h2>";
}
}
//]]>
</script>
</head>
<body>
<h2>Base:</h2> <input type="text" size="25" style="font-size:20pt" id="base" value=""></br>
<h2>Height:</h2> <input type="text" size="25" style="font-size:20pt" id="height" value="">
<br/>
<span id="results"><h2>Enter your answer in the Area box below then click on calculate</h2></span>
</br>
<h1>Area:</h1> <input type="text" size="25" style="font-size:20pt" id="area"> </br>
<input type="button" size="100" style="background-color: red; color:yellow;height:80px;width:140px;font-size:30px; " value="Calculate" onClick="Triarea()"><br>
</body>
</html>
答案 1 :(得分:0)
您正在使用===
严格相等运算符,但让javascript按其类型推断执行所需操作。
使用parseFloat
(或parseInt
,如果您更喜欢整数)将您的值解析为浮点值,让它知道您正在处理的内容。你更有可能得到你期望的结果。请注意,您可能还必须更改该等式检查以包含epsilon检查。
base = parseFloat(document.getElementById('base').value);
height = parseFloat(document.getElementById('height').value);
area = parseFloat(document.getElementById('area').value);
更新了之前发布的小提琴:http://jsfiddle.net/fKSp8/1/