Javascript初学者 - 谁能告诉我为什么我的按钮不起作用?

时间:2014-08-07 19:27:25

标签: javascript

jsfiddle在这里 - > http://jsfiddle.net/diabetesjones/015k1tjn/5/

这是一个有效的例子: http://jsfiddle.net/Ahopefulmachine/dkhj8o38/

关于第二个jsfiddle(不是我的),我不太明白为什么他的作品没有在按钮上使用document.getElementById。

我觉得我的问题出在点击功能本身:

document.getElementById('mainButton').onclick = function () {

谢谢:)

2 个答案:

答案 0 :(得分:2)

立即开始工作:http://jsfiddle.net/doniyor/015k1tjn/9/

您的document.getElementByID应为document.getElementById

AND

  1. 你没有像numberOne = parseInt(numberOne, 10);那样将字符串转换为int,其中10是小数的基数。
  2. 您的question == ADD应为question == 'ADD'

答案 1 :(得分:2)

您的代码有三个问题:

  1. 它是getElementById而非getElementByID(区分大小写)。
  2. 您没有将输入的字符串转换为数字。您可以在+
  3. 前面添加document.getElementById('number1').value;,轻松完成此操作
  4. 您正在对变量进行比较,而不是字符串。前question == ADD代替question == 'ADD'
  5. 请参阅更正 jsFiddle example

    document.getElementById('mainButton').onclick = function () {
    
        //Getting values of inputs and saving them to variables
        var numberOne = +document.getElementById('number1').value;
        var numberTwo = +document.getElementById('number2').value;
    
        //Setting values of the equations
        var addition = (numberOne + numberTwo);
        var subtraction = (numberOne - numberTwo);
        var multiplication = (numberOne * numberTwo);
        var division = (numberOne / numberTwo);
    
        //Prompting user for their desired equation
        var question = prompt("Do you wish to ADD, SUBTRACT, MULTIPLY, or DIVIDE?").toUpperCase();
    
        //If statement to show the proper equation based on the user's prior prompt
        if (question == 'ADD') {
            alert('I added the shit out of those numbers for you - turns out it is ' + addition);
        } else if (question == 'SUBTRACT') {
            alert('Did some of this, some of that, some minusing - your answer is ' + subtraction);
        } else if (question == 'MULTIPLY') {
            alert('Yeah, I multipled the numbers, big whoop, wanna fight abouddit? the answers over there --> ' + multiplication);
        } else if (question == 'DIVIDE') {
            alert('This ones my favorite, I love a good division - ' + division);
        };
    
    };