简体   繁体   中英

How can i get one button to do multiple tasks depending on how many times it has been clicked? (Javascript)

How can i get one button to do multiple tasks depending on how many times it has been clicked? (Javascript)

For example button is clicked - alert "button clicked once" button gets clicked again - alert "button clicked twice" button is clicked again - alert" button has been clicked three times!"

Sorry if its a noob question, the reason is I AM A NOOB!!!

Fiddle demo : http://jsfiddle.net/h9DbF/

in js:

var clickTimes = 0;

function doSomethingOnClick() {
    clickTimes++;
    switch(clickTimes) {
        case 1:
            alert('Button clicked once');
            break;
        case 2:
            alert('Button clicked twice');
            break;
        default:
            alert('Button clicked ' + clickTimes + ' times');
    }
    //Do something else
}

in html:

<button onclick="doSomethingOnClick()">Press me</button>

You could create a var that will increment when the button is clicked, and you can switch that var so you can do an action depending on the number of clicks for example:

var clicks = 0;
function someFunction(){
    clicks++;
    switch (clicks){
        case 1:
            //do something when its clicked only once
            break;
    }
}

And thats it.

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