![](/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.