简体   繁体   中英

javascript calculator (how i make the first click does not accept operation)

how I make the first click does not accept operation and return "0"

Here is my function

$(document).ready(function(){
    $('button').on('click', function(){
        var previosValue = $('.viewer').text();
        var val = $(this).text();
        if(val == "="){
            var op = eval($('.viewer').text());
            $('.viewer').text(op);
        } else if(val == "AC"){
            $('.viewer').text("0");
        } else {
            if($('.viewer').text() == "0"){
                $('.viewer').text(val);
            } else {
                $('.viewer').text(previosValue + val);
            }
        }
    });
});

there is the full code on codepen

First created operators array ops = [ "+", "-", "*", "/", "%" ] . Then compare input value, if input value is any of the operator from above array when first value is zero (0) then return 0.

$(document).ready(function(){
  var ops = [ "+", "-", "*", "/", "%" ]; // operators array
  $('button').on('click', function(){
    var previosValue = $('.viewer').text();
    var val = $(this).text();
    if(val == "="){
      var op = eval($('.viewer').text());
      $('.viewer').text(op); 
    }else if(val == "AC"){
      $('.viewer').text("0");
    }else{
      if($('.viewer').text() == "0"){
        if($.inArray( val, ops ) != -1) { // check there first input with operators
          $('.viewer').text(0);
        } else {
          $('.viewer').text(val);
        }
      }else{
        $('.viewer').text(previosValue + val);
      }
    }
  });
});

I'd suggest you don't swallow a key press when your user clicks on an operation symbol first. Instead, use the initial "0" as the first operand (ie if user clicks "+" when only "0" is displayed, you display "0+").

This has an advantage in that it works as most other calculators do. And in UI design consistency is key.

Something like this should work:

$(document).ready(function(){
  $('button').on('click', function(){
    var previosValue = $('.viewer').text();
    var val = $(this).text();
    if(val == "="){
      var op = eval($('.viewer').text());
      $('.viewer').text(op); 
    } else if(val == "AC"){
      $('.viewer').text("0");
    } else if ($('.viewer').text() != "0" || $.inArray(val, ["/", "*", "-" ,"+"]) > -1){
      $('.viewer').text(previosValue + val);          
    } else {
      $('.viewer').text(val);
    }
  });
});

You also need to check what happens when user presses, for example, "5", "+", "*", "6". Currently it displays "5+*6". You probably want later operand overriding the previous one... But that is an entirely different question ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM