How to increment and decrement using FOR?

-3

I'm not able to increment the variable with each click on a button .

Example: Button and Paragraph , each time you click the button , increase the Paragraph , for example, from 0 to 1, and each click will increment one.

function criaCounter(init) {
    var count = init || 0;
    return function() {
        count++;
        alert(count);
    }
}

$('#addCount').click(criaCounter(5)); 
    
asked by anonymous 23.08.2017 / 22:26

1 answer

2

It's basically a matter of scope.

Just take the variable declaration from the function body, see the code working just below, clicking "run":

var count = 0; // tiramos esta linha da função

function criaCounter(init) {
    count = init || count;
    return function() {
        count++;
        alert(count);
    }
}

$('#addCount').click(criaCounter(5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="addCount">Clique aqui</button>

Note that the for mentioned in your question is not related to what you asked for it to happen. You do not want a loop , but a single action with each click.

Note that I changed count = init || 0; to count = init || count; simply so that we do not zero the value on subsequent calls.

    
23.08.2017 / 22:32