javascriptjqueryhtmlcssself-executing-function

self executing anonymous click function in for loop


I need a click function in a for loop, so every id element is clickable. But I also need the i in the click function, that's why I thought a self executing anonymous function would be the best way to do so. But for some reason this is not working, maybe because the click function doesn't allow me to forward a parameter? What have I done wrong?

for (var i = 0; i < countItems; i++) {     
        $("#item-" + i).click(function(idx) {
           alert(idx);
    })(i)
}

Solution

  • The self executing function must return a function:

    for (var i = 0; i < countItems; i++) {
        $("#item-" + i).click(function(indx){
            return function(){  //must return a function
               alert(indx);
            }
        }(i));
    }
    

    JS Fiddle: http://jsfiddle.net/HuHXr/