gpt4 book ai didi

javascript - 使用 JavaScript 更改 HTML 元素

转载 作者:行者123 更新时间:2023-12-03 07:31:47 24 4
gpt4 key购买 nike

我正在学习 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>

最佳答案

在函数中添加 return false;

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;

// prevent the form from its natural bahavior
return false;
}

如果表单的 onSubmit 事件获取 false,则会阻止表单提交数据。

<form name="Circle" onsubmit="return printCircle();" method="post">
<小时/>

或者,您可以用更好、最有效的方式做到这一点。

var printCircle = function(){
event.preventDefault();
...
}

然后:

<form name="Circle" onsubmit="printCircle();" method="post">

Read more

关于javascript - 使用 JavaScript 更改 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com