Why does the global variable fixed in the closure of the $ .get () callback always have the same value?

I am having trouble getting the value of a global variable in my $.get() :

Appropriate markup

 <div class="block" id="blog"></div> <div class="block" id="music"></div> <div class="block" id="video"></div> 

Relevant Code

 $('div.block').each(function() { $this_id = $(this).attr('id'); alert($this_id); // outputs: blog, music, video $.get('test.php', {id: $this_id}, function(data) { alert($this_id); // outputs: blog, blog, blog (WHY?) $('div#' + $this_id).html(data); }); }); 

I am trying to get the HTML content and embed it in each of the block div, but $ this_id does not change inside the call to $.get() , Can anyone explain this?

0
source share
1 answer

You need to define $ this_id within the scope or by default it will be a global variable. Just change this:

 $this_id = $(this).attr('id'); 

:

 var $this_id = $(this).attr('id'); 

It’s a good idea to get used to explicitly declaring all your variables anyway ... It’s much easier to track them that way.

0
source

All Articles