[英]Calculating a total using (JavaScript and HTML)
我正在為游戲創建一個計算器,並且有一個下拉菜單可以在switch語句中選擇一個值。 盡管我不確定如何計算總數。 誰能看得到嗎?
http://jsfiddle.net/newto98/8xLo9m9u/
這是我的HTML:
<!-- Witch /-->
<div style="display: inline;">
<form style="display: inline;">
<!-- Title of Form /--> <font>Level</font>
<!-- Gets Input /-->
<select id="witchlevel_input">
<option>0</option>
<option>1</option>
<option>2</option>
</select>
<!-- Calls 'calcwitch' /-->
<input type="button" value="Calculate" onclick="return calcwitch(document.getElementById('witchlevel_input').value)">
<!-- Outputs result /--> <span id="witchcost_result"> = 0 Dark Elixer</span>
</form </div>
<br></br>
<!-- Lava Hound /-->
<div style="display: inline;">
<form style="display: inline;">
<!-- Title of Form /--> <font>Level</font>
<!-- Gets Input /-->
<select id="lavalevel_input">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<!-- Calls 'calclava' /-->
<input type="button" value="Calculate" onclick="return calclava(document.getElementById('lavalevel_input').value)">
<!-- Outputs result /--> <span id="lavacost_result"> = 0 Dark Elixer</span>
</form </div>
<br></br>
<!-- Total /-->
<div style="display: inline;">
<form onsubmit="return calctotal(0);" style="display: inline;">
<!-- Title of Form /-->
<font>Total Cost</font>
<!-- Calls 'calcWalls' /-->
<input type="button" value="Calculate" onclick="calctotal();">
<!-- Outputs result /-->
<span id="total_result"> = 0 Elixer</span>
</form>
這是我的javascript:
<script>
function calcwitch(witchlevel) {
var witchString;
switch (witchlevel) {
case '0':
witchString = "75000";
break;
case '1':
witchString = "75000";
break;
case '2':
witchString = "0";
break;
}
document.getElementById("witchcost_result").innerHTML = "= " + Math.round(parseInt(witchString) * 100) / 100 + " Dark Elixer";
}
function calclava(lavalevel) {
var lavaString;
switch (lavalevel) {
case '0':
lavaString = "130000";
break;
case '1':
lavaString = "130000";
break;
case '2':
lavaString = "70000";
break;
case '3':
lavaString = "0";
break;
}
document.getElementById("lavacost_result").innerHTML = "= " + Math.round(parseInt(lavaString) * 100) / 100 + " Dark Elixer";
}
</script>
快速,也許不是最優雅的解決方案
只需從2個函數中返回數字值,然后在calctotal()
使用返回值
說到更好的性能,我將計算拆分為一個函數,將DOM操作拆分為另一個。 我的小提琴現在無緣無故地重寫了2個元素的innerHTML ...
使用document.getElementById(“”)。value計算前兩個LEVEL時,請使用兩個隱藏字段並為其設置值。 然后,當單擊總成本時,使用函數將這兩個值相加,然后使用document.getElementById(“”)。innerHTML設置為最后一個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.