0

I want to repeat a jquery function dynamically for n-numner of times. Alert is working for the number of count but function is not created as many times. My code is as below

        var count = 5;
        var i = 1;
        for (var i = 1; i <= count; i++)
        {
            var min = ".min" + i;
            alert(min); // Just for testing purpose, working good
            document.writeln(min); // Just for testing purpose, working good
            alert(i); // Just for testing purpose, working good

            // Following function does not get repeated, 
            $(document).ready(function () {
                $("min" + i).click(function () {
                    alert(i);
                });
            });
        }

My body section code is as follows

 <div class="min1"> Test - 1 </div>
 <div class="min2"> Test - 2 </div>
 <div class="min3"> Test - 3 </div>
 <div class="min4"> Test - 4 </div>

This may look simple but I need someone's guide to get it done. Please help me to make it work. This is just a concept which I am going to implement on a large basis in my project. Thanks in advance.

Shashi Roy
  • 323
  • 3
  • 7
  • 22

1 Answers1

3

Although the problem in your code is the wrong use of closure in a loop.

The solution can be different, you can use a common click handler for all the elements then use a data-* attribute to store the dynamic value that is needed in the click handler.

$(document).ready(function() {
  $(".min").click(function() {
    alert($(this).data('id'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="min1 min" data-id="1">Test - 1</div>
<div class="min2 min" data-id="2">Test - 2</div>
<div class="min3 min" data-id="3">Test - 3</div>
<div class="min4 min" data-id="4">Test - 4</div>
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531