How to increment and decrease using FOR?

Asked

Viewed 286 times

-3

I’m not getting to increment the variable with each click on one button.

Example: a Button and a Paragraph, every click on button, increase the value in Paragraph, example, from 0 to 1, and each click increments one.

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

$('#addCount').click(criaCounter(5)); 

1 answer

2

It’s basically a matter of scope.

Just take out the variable declaration from the body of the function, see the code working just below by clicking on "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>
<button id="addCount">Clique aqui</button>

Note that the for mentioned in your question does not bear any relation to what you asked for to happen. You do not want a loop, and yes a single action every click.

Note that I changed the count = init || 0; for count = init || count; simply not to reset the value in the following calls.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.