JSFiddle - React, Tailwind, and code Playground

by Coridyn

HTML

<div class="correct" style="border: 1px solid green">
    <p>Correct: Clicking an item will show the value of 'i' when the handler was created. i.e. click 'aa' will show 1, click 'jj' with show 10.</p>
    <div class="1">aa</div>
    <div class="2">bb</div>
    <div class="3">cc</div>
    <div class="4">dd</div>
    <div class="5">ee</div>
    <div class="6">ff</div>
    <div class="7">gg</div>
    <div class="8">hh</div>
    <div class="9">ii</div>
    <div class="10">jj</div>
    <p class="result"></p>
</div>

JavaScript

// Setup click handlers for the 'correct' divs.
for (var i = 1; i <= 10; i++){
    
    // 1. Create an anonymous self-invoking function that
    // returns a function.
    var callback = (function(){
        
        // 2. Copy the current value of 'i' to a new variable so
        // that changes to 'i' cannot affect us.
        var currentI = i;
        
        // 3. Return the function definition that
        // will be bound to the event listener.
        return function(e){
            var t = $(this).text();
            
            // 4. NOTE that we reference 'currentI' and not 'i' here.
            $(".correct .result").text("You clicked div: class='"+currentI+"' content='"+t+"'");
        };
    }());
    
    $(".correct ."+i).click(callback);
}