我正在编写一个函数来根据选择框中选择的值计算总和。如何使下面的JavaScript代码更简洁?
<select name="test" id="mySelect1" style="font-size:10px" onchange="Calculate()">
<option value="onePoint">1</option>
<option value="halfPoint">1/2</option>
</select>
<select name="test" id="mySelect2" style="font-size:10px" onchange="Calculate()">
<option value="onePoint">1</option>
<option value="halfPoint">1/2</option>
</select>
function Calculate()
{
var selectedValue1 = document.getElementById("mySelect1").value;
var selectedValue2 = document.getElementById("mySelect2").value;
if (selectedValue1 == "onePoint" && selectedValue2 == "onePoint")
{
var total = 2;
}
else if (selectedValue1 == "halfPoint" && selectedValue2 == "halfPoint")
{
var total = 1;
}
else if (selectedValue1 == "onePoint" && selectedValue2 == "halfPoint")
{
var total = 1.5;
}
else if (selectedValue1 == "halfPoint" && selectedValue2 == "onePoint")
{
var total = 1.5;
}
document.getElementById("demo").innerHTML = total;
}
答案 0 :(得分:2)
const selectedValue1 = document.getElementById("mySelect1").value === "onePoint" ? 1 : 0.5;
const selectedValue2 = document.getElementById("mySelect2").value === "onePoint" ? 1 : 0.5;
const total = selectedValue1 + selectedValue2;
您可以使用三元组(?
)将值转换为数字,然后您只需添加它们即可。
答案 1 :(得分:2)
假设只有几个不同的值:
var values = {
onePoint: 1,
halfPoint: 0.5
}
function Calculate() {
var value1 = values[document.getElementById("mySelect1").value];
var value2 = values[document.getElementById("mySelect2").value];
document.getElementById("demo").innerHTML = value1 + value2;
}