使用javascript和html表单计算两点之间的距离[重复]
Posted
技术标签:
【中文标题】使用javascript和html表单计算两点之间的距离[重复]【英文标题】:calculate distance between two points using javascript & html form [duplicate] 【发布时间】:2018-09-04 01:06:39 【问题描述】:在输入 x1,x2,y1,y2 的数字后单击“计算距离”按钮时,我有点卡住了,一切都会清除而不是计算
function calculateDistance()
var pointx1 = parseInt(document.getElementById("pointx1").value);
var pointy1 = parseInt(document.getElementById("pointy1").value);
var pointx2 = parseInt(document.getElementById("pointx2").value);
var pointy2 = parseInt(document.getElementByID("pointy2").value);
var distance = Math.sqrt(Math.Pow((pointx1-pointx2),2)+Math.Pow((pointy1-pointy2),2));
window.alert("Distance: "+distance);
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> Distant Points </title>
<script type = "text/javascript"> </script>
</head>
<body>
<form name = "f1" method="post">
<label>Point 1:</label><br>
x:<input type = "text" id = "pointx1" size = "30"/> y1:<input type = "text" id = "pointy1" size = "30"/> <br>
<label>Point 2:</label> <br>
x:<input type = "text" id = "pointx2" size = "30"/> y2:<input type = "text" id = "pointy2" size = "30"/>
<button onclick = "calculateDistance()">Calculate Distance</button>
</form>
</body>
</html>
【问题讨论】:
你注意到你拼错了最后一个getElementByID
吗?此外,在您的<button>
上使用type="button"
。否则,您的 <form>
将被提交,这不是您想要的。
document.getElementByID()
应该是 document.getElementById()
。 Math.Pow()
也应该是 Math.pow()
。在这两种情况下。您可能还想阻止默认表单提交。
看来您正在提交表单。只需停止事件传播。
【参考方案1】:
原因是你有几个错别字,而且你使用的是一个表单。
首先是错别字:
这是document.getElementById
不是document.getElementByID
其次,是Math.pow
而不是Math.Pow
由于按钮位于表单中,您还需要return false
以防止默认表单提交会干扰您的代码。
function calculateDistance()
var pointx1 = parseInt(document.getElementById("pointx1").value);
var pointy1 = parseInt(document.getElementById("pointy1").value);
var pointx2 = parseInt(document.getElementById("pointx2").value);
var pointy2 = parseInt(document.getElementById("pointy2").value);
var distance = Math.sqrt(Math.pow((pointx1-pointx2),2)+Math.pow((pointy1-pointy2),2));
window.alert("Distance: "+distance);
<form name = "f1" method="post">
<label>Point 1:</label><br>
x:<input type = "text" id = "pointx1" size = "30"/> y1:<input type = "text" id = "pointy1" size = "30"/>
<br>
<label>Point 2:</label> <br>
x:<input type = "text" id = "pointx2" size = "30"/> y2:<input type = "text" id = "pointy2" size = "30"/>
<button onclick = "calculateDistance(); return false;">Calculate Distance</button>
</form>
【讨论】:
以上是关于使用javascript和html表单计算两点之间的距离[重复]的主要内容,如果未能解决你的问题,请参考以下文章