简体   繁体   中英

Unsure of how to make this calculator function work

Link to Codepen

For a math project due very soon.

I've tried to apply the DRY concept, but I don't know how. I started to write a function that would apply for all of the numbers, but halfway through it I realized there's no way it would work. The anonymous functions need to be changed I know that, yet I can't right now as I don't know another way to implement it.

document.querySelector(".button").addEventListener("click", function) {
  num = document.getElementById('something'); 

  if (num != null && num === document.getElementById("zero")) {
    calculation = calculation.concat("0");
  } else if (num != null && num === document.getElementById("one")) {
    calculation = calculation.concat("1");
  } else if (num != null === && num document.getElementbyId("two")) {
    calculation = calculation.concat("2");
  } else if (num != nul && num === document.getElementbyId("three")) {
    calculation = calculation.concat("3");
  } else if (num != nul && num === document.getElementbyId("four")) {
    calculation = calculation.concat("4");
  } else if (num != nul && num === document.getElementbyId("five")) {
    calculation = calculation.concat("5");
  } else if (num != nul && num === document.getElementbyId()) {
    calculation = calculation.concat("6");
  }
}

Each number is inside a button which is inside a table. They also have id's identifying which number they are. I'm not looking for code, don't want to plagiarize anything. Just looking for suggestions on what I could do differently.

Your easiest method will be writing a common function:

 var buttons = document.querySelectorAll("button"); for (var i = 0; i < buttons.length; i++) { buttons[i].addEventListener( "click", function() { var current_value = this.innerHTML; //typed single number var display_value = document.getElementById('display').value; //the value on the calculator display var new_value = display_value + '' + current_value; //+''+ to make it string document.getElementById('display').value = new_value; }); } 

Try this and add exceptions and calculation functions with same method as above by filtering '+','-', etc. values.

i think its easier if you use jquery..just a suggestion.

please see the fiddle.

i have added a class 'show' to all buttons which we want to display on the screen on click and class 'calc' for all operator buttons..replaced your display javascript with the following jquery

var calculation='';
$('button.show').click(function(){
 calculation = calculation.concat($(this).text());
 $('#screen').text(calculation);
});

And also added scripts for the calculation

Please see the fiddle Updated Fiddle

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