![](/img/trans.png)
[英]How to reuse a function in javascript with different variables
[英]reuse function with different variables
我想重用我的函数而不必复制粘贴相同的代码
所以我希望用户输入一个值
单击按钮调用 function 并计算结果
然后输入另一个值并单击不同的按钮调用 function 并计算结果
如下所示
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>
我也是 javascript 中的菜鸟,所以对此持保留态度。 首先我会改变 calcPG function
将 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;
添加 `` 和 ${ } 这样如果你调用 CalcPG(1) 你会得到例如“div1depth”
并对 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.