[英]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.