我试图制作一个基本计算器,根据从下拉菜单中选择的运算符进行数学计算,但它不起作用。我不确定为什么它不起作用。我试图接收所选项目的索引,而不是实际文本。
我的代码:
var numOne = document.getElementById("num-one");
var numTwo = document.getElementById("num-two");
var menu = document.getElementbyId("menuType"); // feeling like the error is here
var selection = menu.options[menu.selectedIndex].value; // or here
var userAnswer = document.getElementById("user-Answer");
numOne.addEventListener("input", math);
numTwo.addEventListener("input", math);
function math() {
var one = parseFloat(numOne.value) || 0;
var two = parseFloat(numTwo.value) || 0;
var userSelect = selection
if (userSelection == 1){
userAnswer.innerHTML = one + two;
}
else if (userSelection == 2){
userAnswer.innerHTML = one - two;
}
else else if (userSelection == 3){
userAnswer.innerHTML = one * two;
}
else else else if (userSelection == 2){
if (two == 0){
alert("Error, cannot divide by 0");
}
else
userAnswer.innerHTML = one / two;
}
}
答案 0 :(得分:0)
您可以使用selectedIndex
在下拉列表中返回所选选项的索引。
例如:document.getElementById("numOne").selectedIndex = "1";