X10nD
X10nD

Reputation: 22040

How do I get "I" to increment inside a .click function

$('#x').click(function() {
var i=1;

    $('#y').prepend('<div id='+i+'>x'+i+'</div>');
    i++;        
});

I want the i to increment, now for some reason it is not. I will agree this is a silly question.

Upvotes: 0

Views: 44

Answers (2)

paulslater19
paulslater19

Reputation: 5917

Try not to litter the global scope. This solution will encapsulate i, but still retain its value

$('#x').click((function() {
    var i = 1;
    return function () {
        $('#y').prepend('<div id='+i+'>x'+i+'</div>');
        i++;        
    }
})());

Example: http://jsfiddle.net/Hxw3q/

Upvotes: 0

antyrat
antyrat

Reputation: 27765

Place var i before the click scope:

var i=1;
$('#x').click(function() {
    $('#y').prepend('<div id='+i+'>x'+i+'</div>');
    i++;        
});

Upvotes: 4

Related Questions