Ok, below is my code:
for (var mycounter = currentcanvas.getObjects().length; mycounter > 0; mycounter--) {
var id = currentcanvas.getObjects().length - mycounter;
alert(id);
$("#frontlayers").prepend('<li id="' + id + '" class="layers"></span> Layer ' + (id + 1) + ': ' + " " + ' </li>');
$("#" + id).click(function(e) {
alert(id);
});
}
This correctly adds the li with the text "Layer 1" and "Layer 2", but when I click on them the alert is always 2 instead of 0 and 1 accordingly. does anyone know why this is happening? sorry I'm relatively new to jQuery.
alert(this.id)- within the click handlerthiswill be the clicked element. The problem you're having with the variableidis that all of the click handlers you create refer to the same variable as per the question pimvdb linked to (which is not a jQuery issue).