2

I have a few div with id(div1,div2,div3,div4). I want to know which div is selected in order to replace the previous selected div (default selected div is div1).

jQuery:

var current;

for(var i = 2; i <= 10; i++) {

if(current == "")
    current = "#div1";

$("#div" + i).click(function(e) {

    alert(i);
    $(current).replaceWith($('#div' + i));
    $('#div' + i).attr('id',current);

    current = "#div" + i;

    alert(current);

   });
}

However when i do this, the loop do run through 1-10 BUT when i alert i inside the click function, it return me 11! How can number 11 be inside the loop!Can you please correct me?

  • It is not inside the loop (It is inside the click function). Here after the loop ends the value of `i` is 11. And now when you click the div, the click function gets executed. Now the scope of i is still live and its value is 11. the `alert(i)` is giving you 11. your loops is correectly executing. – rhitz Dec 31 '15 at 03:00
  • @RohitTotala Why not inside the loop? The bracket is cover everything – Yan Shuang Low Dec 31 '15 at 03:03
  • Click function is event listener which gets executed on click event of the element. Your loop got executed correctly. Now whenever you click the div, the click function only gets executed. If you click multiple time it will execute multiple times (but only the click function) – rhitz Dec 31 '15 at 03:09

0 Answers0