使用javascript和amp;计算两点之间的距离HTML表单

时间:2018-03-25 23:37:51

标签: javascript html

在输入x1,x2,y1,y2的数字后,每当我点击“计算距离”按钮时,我都会陷入困境,所有内容都清除而不是计算

<!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>
yy=plot(Xlink,Ylink,'color',rgb('light blue'),'MarkerSize',25);

1 个答案:

答案 0 :(得分:2)

原因是你有几个拼写错误,并且你正在使用表格。

首先是拼写错误:

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

由于该按钮位于表单中,因此您还需要return false来阻止默认表单提交,这会干扰您的代码。

&#13;
&#13;
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);
}
&#13;
<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>
&#13;
&#13;
&#13;