I have 4 css classes that are named a particular way : test-class-0, test-class-1, test-class-2, test-class-3 so that I can register custom click handlers programmatically.
Here is my attempt:
for(var i = 0; i < 4; i++) {
$('.test-class-'+i).on('click', function(e){ alert(i); });
}
Full demo:
for (var i = 0; i < 4; i++) {
$('.test-class-' + i).on('click', function(e) {
alert(i);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test-class-0">TEST 1</div>
<div class="test-class-1">TEST 2</div>
<div class="test-class-2">TEST 3</div>
<div class="test-class-3">TEST 4</div>
The events get registered, however, the handler will always use the latest value of i, which is 4, when I would like the value of i on the time of handler registration, so I get alert(0), alert(1), alert(2), and alert(3) when I click on test-class-0, 1, 2, 3 respectively.
Is there a way I can lock down the value of i within the function when the click handler is registered?