0

这是我的代码

 document.getElementsByName('submitButton').onclick = function(event) {
  event.preventDefault();

  var num1 = parseFloat(document.getElementsByName('valueA')[0].value),
      num2 = parseFloat(document.getElementsByName('valueB')[0].value),
      arithmeticOperator = document.getElementsByName('arithmeticOperator')[0].value,
      output = document.getElementsByName('result');

  switch(arithmeticOperator) {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        if(num2 != 0)
        {
            result = num1 / num2;
        }else {
            result = 'Dela inte med 0!';
        }
        break;
    default:
        result = 'Error';
  }
  window.alert(result);
  return false;
};

我的问题是我无法让我的代码生成带有答案的弹出窗口。当我在我的 html 中使用 ID 时,它工作正常,但我想了解 getElementsByName 是如何工作的。所以,我根本不想更改我的 HTML,但我需要 JS 方面的帮助。

4

1 回答 1

0

getElementsByName returns an array like object so you need to get the element by index and add the listener

document.getElementsByName('submitButton')[0].onclick = function(event) {
}

Note: In your page, I'm not able to see the button with the said name


Since you have a form, it is better to use the form's submit event

document.getElementById('calcForm').onsubmit = function (event) {
    event.preventDefault();

    var num1 = parseFloat(document.getElementsByName('valueA')[0].value) || 0,
        num2 = parseFloat(document.getElementsByName('valueB')[0].value) || 0,
        arithmeticOperator = document.getElementsByName('arithmeticOperator')[0].value,
        output = document.getElementsByName('result');

    switch (arithmeticOperator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                result = 'Cant devide bu 0';
            }
            break;
        default:
            result = 'Error';
    }
    document.getElementsByName('result')[0].innerHTML = result;
};

Demo: Fiddle

于 2015-04-27T08:33:12.017 回答