Each time I click a button, I want to add +1 to a variable.
For example: I have a count
variable getting a value of 5, when I click a button I want the value 5 to change to 6 and so on, displaying in alert()
.
Is it possible?
Each time I click a button, I want to add +1 to a variable.
For example: I have a count
variable getting a value of 5, when I click a button I want the value 5 to change to 6 and so on, displaying in alert()
.
Is it possible?
Would this be?
HTML:
<input type=button id=addCount value="Adicionar Count">
Javascript:
var count = 5;//recebendo o valor 5 que você disse
$('#addCount').click(function(){
alert(count);
count++;
});
One more option, using closure. This is basically what Paulo Roberto did, but without a global variable:
function criaCounter(init) {
var count = init || 0;
return function() {
count++;
alert(count);
}
}
// Cria contador que começa em 5, e usa como listener do click
$('#addCount').click(criaCounter(5));
I could do something like this:
<button id="count" data-valor="5">Clique Aqui!</div>
$('#count').click( function ( ) {
var valorVelho = this.data('valor');
var valorNovo = valorVelho++;
this.data('valor', valorNovo);
alert( valorNovo );
} );
Since the base is of the count
variable, you can do something like this:
HTML
<button id="count">Clique Aqui!</div>
jQuery
var count = 5;
$('#count').click( function ( ) {
count++;
alert( count );
}