gpt4 book ai didi

javascript - 使用javascript和html表单计算两点之间的距离

转载 作者:行者123 更新时间:2023-12-01 02:16:21 25 4
gpt4 key购买 nike

我有点卡住了,因为每当我在输入 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"/> &nbsp; y1:<input type = "text" id = "pointy1" size = "30"/> <br>
<label>Point 2:</label> <br>
x:<input type = "text" id = "pointx2" size = "30"/> &nbsp; y2:<input type = "text" id = "pointy2" size = "30"/>
<button onclick = "calculateDistance()">Calculate Distance</button>
</form>
</body>
</html>

最佳答案

原因是因为您有多个拼写错误,并且您使用的是表单。

首先是错别字:

这是document.getElementById而不是document.getElementByID其次,它是 Math.pow 而不是 Math.Pow

由于按钮位于表单内,您还需要返回 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"/> &nbsp; y1:<input type = "text" id = "pointy1" size = "30"/>
<br>
<label>Point 2:</label> <br>
x:<input type = "text" id = "pointx2" size = "30"/> &nbsp; y2:<input type = "text" id = "pointy2" size = "30"/>
<button onclick = "calculateDistance(); return false;">Calculate Distance</button>
</form>

关于javascript - 使用javascript和html表单计算两点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482116/

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