简体   繁体   English

用不同的变量重用 function

[英]reuse function with different variables

I want to reuse my functions without having to copy-paste the same code我想重用我的函数而不必复制粘贴相同的代码

so I want the user to input a value所以我希望用户输入一个值

click a button to call the function and calculate a result单击按钮调用 function 并计算结果

then enter another value and click a different button to call the function and calculate a result然后输入另一个值并单击不同的按钮调用 function 并计算结果

as shown below如下所示

 function CalcPG() { var depth, time, pg; depth = Number(document.getElementById("dive1depth").value); time = Number(document.getElementById("dive1time").value); sum = depth + time; prod = depth * time document.getElementById("sum").value = sum; document.getElementById("prod").value = prod; }
 <h1>Calculation 1</h1> <label>Enter depth:</label> <input id="dive1depth" type="number" placeholder="depth"><br> <br> <label>Enter time:</label> <input id="dive1time" type="number" placeholder="time"><br> <br> <button onclick="CalcPG()">Calculate Pressure Group</button> <p>The Sum is: <output id="sum" size="40"></output></p> <p>The Product is: <output id="prod" size="40"></output></p> <:-- BREAK --> <h1>Calculation 2</h1> <label>Enter depth:</label> <input id="dive2depth" type="number" placeholder="depth"><br> <br> <label>Enter time:</label> <input id="dive2time" type="number" placeholder="time"><br> <br> <button onclick="CalcPG()">Calculate Pressure Group</button> <p>The Sum is: <output id="sum2" size="40"></output></p> <p>The Product is: <output id="prod2" size="40"></output></p>

I am also a noob in javascript, so take this with a grain of salt.我也是 javascript 中的菜鸟,所以对此持保留态度。 Firstly i would change the calcPG function首先我会改变 calcPG function

change the function function CalcPG(x) to take ax argument ( x = 1, x =2 and so on...)将 function function CalcPG(x) 更改为采用 ax 参数( x = 1,x =2 等等...)

depth = Number(document.getElementById(`dive${x}depth`).value);  
time  = Number(document.getElementById(`dive${x}time`).value);   

document.getElementById(`sum${x}`).value = sum;  
document.getElementById(`prod${x}`).value = prod;

adding `` and ${ } so that if you call CalcPG(1) you get for example "div1depth"添加 `` 和 ${ } 这样如果你调用 CalcPG(1) 你会得到例如“div1depth”

And making some changes on HTML并对 HTML 进行一些更改

    <button onclick="CalcPG(1)">Calculate Pressure Group</button>
    <p>The Sum is: <output id="sum1" size="40"></output></p>
    <p>The Product is: <output id="prod1" size="40"></output></p>


    <button onclick="CalcPG(2)">Calculate Pressure Group</button>
    <p>The Sum is: <output id="sum2" size="40"></output></p>
    <p>The Product is: <output id="prod2" size="40"></output></p>
   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM