JSFiddle - React, Tailwind, and code Playground

by Coridyn

HTML

<div class="wrong" style="border: 1px solid red">
    <p>Incorrect: Clicking any item will show the last value of 'i'. i.e. class='11'</p>
    <div class="1">a</div>
    <div class="2">b</div>
    <div class="3">c</div>
    <div class="4">d</div>
    <div class="5">e</div>
    <div class="6">f</div>
    <div class="7">g</div>
    <div class="8">h</div>
    <div class="9">i</div>
    <div class="10">j</div>
    <p class="result"></p>
</div>

JavaScript

// Setup click handlers for the 'incorrect' divs.
for (var i = 1; i <= 10; i++){
    $(".wrong ."+i).click(function(){
        var t = $(this).text();
        
        // This doesn't work because all of the handlers reference the same 'i' variable.
        // When the loop finishes 'i == 11' so when you click on any of the divs they output the current value of 'i' which is eleven.
        $(".wrong .result").text("You clicked div: class='"+i+"' content='"+t+"'");
    });
}