0

I have the javascript function in my jsp page as

<script type="text/javascript">
$(document).ready(function(){
for(i=0; i<20; i++ ) {
$(".plus"+i).click(function(){
    $(".details"+i).slideToggle(500)
    });
}
});

for each iteration i want the output like this:

.plus0 .details0

Next iteration :

.plus1 .details1 and so on. But this is not working. Please help.

2 Answers2

2

There will be no error in the console. The issue is that by the time the click handler has been triggered, the for() loop has already completed, so i will always equal 19.

You can circumvent this behaviour using event data in jQuery. You can update your code as follows:

$(function() {
    for( i = 0; i < 20; i++ ) 
    {
        $('.plus' + i).click( { theIndex : i }, function(e) {
            $('.details' + e.data.theIndex).slideToggle(500)
        });
    }
});
BenM
  • 52,573
  • 26
  • 113
  • 168
  • Actually, on jsp page i have mulitple plus icon. Some items are hooked with each plus icon. On clicking that plus icon that particular data should be displayed. The data is hooked in details div tag. So on clicking plus0 the corrosponding details 0 should be displayed and so on. For that i have written the js file as given above. I have tried your solution also. But still getting the same issue. – user3443612 Jan 29 '15 at 11:43
  • @user3443612 Without seeing your markup, it's impossible to better answer your question I'm afraid. – BenM Jan 29 '15 at 11:52
1

The problem is caused because you are using closures. The reference of i is held by the click event handler. So the latest value of i is seen by all event handlers.

To solve the problem, write a factory function that returns an event handler.

var createEventHandler = function (param1) {
    return function (e) {
       $(".plus"+param1).click(function(){
           $(".details"+param1).slideToggle(500)
       });
    } 
}

$(document).ready(function(){
    for(i=0; i<20; i++ ) {
       $(".plus"+i).click(createEventHandler(i));
    }
});

Read about closure variables.

Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21
  • 1
    There's no need to use a factory function. You can just pass in the value of `i` as event data. – BenM Jan 29 '15 at 11:27
  • Actually, on jsp page i have mulitple plus icon. Some items are hooked with each plus icon. On clicking that plus icon that particular data should be displayed. The data is hooked in details div tag. So on clicking plus0 the corrosponding details 0 should be displayed and so on. For that i have written the js file as given above. I have tried your solution also. But still getting the same issue. – user3443612 Jan 29 '15 at 11:43