【发布时间】:2016-06-17 15:58:53
【问题描述】:
我正在学习 JavaScript,我正在尝试创建一个“圆形计算器”,它将通过表单获取用户输入并返回给他们圆形的面积和周长。 除了在 ID 为“circleData”的段落中显示结果之外,这一切都有效。它在提交表单后显示几分之一秒然后消失。
我希望 Circle 方法的结果(变量“文本”)保留在段落中,直到用户再次提交表单(当它应该填充新数据时)。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Test</title>
</head>
<body>
<h1>A Circle Calculator</h1>
<form name="Circle" onsubmit="printCircle()" method="post">
Enter the radius:<br>
<input type="text" name="Radius"><br><br>
Enter the units:<br>
<input type="text" name="Units"><br><br>
<input type="submit" value="Submit"><br>
</form>
<p id="circleData"></p>
<script type="text/javascript">
var Circle = function(radius){
this.radius = radius;
}
Circle.prototype = {
get _radius(){
return this.radius;
},
get _area(){
return Math.PI * (this.radius * this.radius);
},
get _perim(){
return this.radius * (Math.PI * 2);
},
set _radius(radius){
this.radius = radius;
}
}
var aCircle = new Circle();
var printCircle = function(){
aCircle._radius = document.forms["Circle"]["Radius"].value;
var units = document.forms["Circle"]["Units"].value;
var text = "A circle with the radius of " + aCircle._radius + units + " has a circumference of " + aCircle._perim.toFixed(2) + units + " and an area of " + aCircle._area.toFixed(2) + units;
document.getElementById("circleData").innerHTML= text;
}
</script>
</body>
</html>
【问题讨论】:
-
那是因为
form被提交了。在printCircle()或event.preventDefault()末尾使用return false;。 -
@Tushar 这将是完全合理的答案而不是评论。您可能想重新提交它作为答案,这样我们就可以通过投票和接受它来为您提供更多声誉积分。
-
虽然其他答案都是正确的,但这也会显示您想要的结果,只是无需提交您的表单并直接进行计算:
... <form name="Circle" method="post"> Enter the radius:<br> <input type="text" name="Radius"><br><br> Enter the units:<br> <input type="text" name="Units"><br><br> <input type="button" value="Submit" onclick="printCircle();" ><br> </form> <p id="circleData"></p> ...
标签: javascript html