I am familiar with JavaScript closures. I discovered closure issues while working on my own projects, years ago. I have also included the famous for-loop-button question while interviewing candidates.
Now, I got asked this question with jQuery. And I cannot, for the life of me, solve the problem.
$(document).ready( function() {
var buttons = $('button');
for( var i = 0; i < buttons.length; ++i ) {
buttons.eq(i).click(
// ONLY EDIT THE CODE BELOW THIS LINE
function() {
$('ul').append('<li>' + i + '</li>')
}
// ONLY EDIT THE CODE ABOVE THIS LINE
);
}
});
Does anyone know how to create the necessary closure here, within the constraints?
I tried wrapping the anonymous function in parenthesis, returning an inner function, etc. Nothing worked.
https://jsfiddle.net/hmw0gk4c/791/
Thanks.