首页 > 解决方案 > 在 HTML 代码中按下按钮时如何触发 JavaScript 函数

问题描述

我正在尝试创建一个解决毕达哥拉斯定理的计算器。我在我的代码中的标签内创建了一个函数,它接受两个参数(一个用于直角三角形的每条腿长度)如果我只使用两个数字作为参数的 console.log 并且函数在以下情况下正确执行,则该函数有效它在脚本标签内。但我只想知道如何在文本框中获取两个参数,然后当我按下按钮时,结果会出现在屏幕上。

<html>
  <main>
    <head>
        <!--Textboxes to input lengths of legs-->

        <input type = "text" required placeholder= "1st legnth">
        <br> <br>
        <input type = "text" required placeholder= "2nd legnth">
        <br> <br>
        <button type = "submit">Give me the answer.
    </head>
   </main>
</html>


 <script>


    function solveforHyp (a, b)
    {

     var c = a*a + b*b;

     return Math.sqrt(c);

     }

     var final = (solveforHyp(3, 4));

     console.log(final);

     </script>

标签: javascripthtmlfunction

解决方案


要调用的js文件函数

function tryMe(arg) {
    document.write(arg);
}

文件

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src='object.js'> </script>
    <title>abc</title><meta charset="utf-8"/>
</head>
<body>
    <script>
    tryMe('This is me vishal bhasin signing in');
    </script>
</body>
</html>

推荐阅读