简体   繁体   中英

Javascript how do i keep track of event when a button is clcked

I am a writing a web base calculator using java-script i have created my buttons and linked them the event that should occur if that particular button was click for example if button 3 was click 3 will appear on the screen, if addition sign was click it will appear on the screen so my problem is to keep track of all the button click and perform mathematical operations on them when a user hits the equalto button and result displayed on the screen for example 3 + 3 = 6. My problem now is to ensure that user inputs should be stored in a function which i can invoke be pressing the equalto symbol on the calculator here is and example of one of my event functions which is tied to the button one

<button onclick="one()">1</button> 

function one(){
            var x = document.getElementById('screen')//Gets the value of html content
            if (x.innerHTML == '0'){
                x.innerHTML = 1
            }
            else{
                var x = document.getElementById('screen').innerHTML += 1
            }
            if (x.length > 20){
                var x = document.getElementById('screen').innerHTML = 'ERROR' 
            }
        }

I am have a function name calculate which is tied to the equalto button how can i keep track of buttons events that is numbers and mathematical symbols in this function such that when a user hits this button the result should be displayed on the screen

function calculate(){


            }

这是应用程序的图片 ] 1

You can maintain a array to keep track all your click on calculator

const buttonClicked = [];

<button onclick="buttonClicked(1)">1</button> 

once any button is clicked

function buttonClicked (key) {
buttonClicked.push(key);
}

inside calculate function try to read the value from buttonClicked array based on that try to do which ever operation you want to do.

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