我正在为游戏创建一个计算器,并且有一个下拉菜单,可以在 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 操作拆分为另一个函数。我的 fiddle 现在无缘无故地多余地重写了 2 个元素的innerHTML...
关于javascript - 使用(JavaScript 和 HTML)计算总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114150/