我想重用我的函式而不必復制粘貼相同的代碼
所以我希望用戶輸入一個值
單擊按鈕呼叫函式并計算結果
然后輸入另一個值并單擊不同的按鈕來呼叫函式并計算結果
如下所示
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>
uj5u.com熱心網友回復:
我也是 javascript 的菜鳥,所以對此持保留態度。首先我會改變 calcPG 功能
更改函式函式 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/416734.html
標籤:
