Why does a global variable captured in a $.get() callback closure always hold the same value?

心已入冬 提交于 2019-12-24 18:36:05

问题


I'm having a bit of trouble capturing the value of a global variable in my $.get() callback:

Relevant 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'm trying to get HTML content and insert it into each of the block divs, but $this_id doesn't get changed inside the call to $.get(). Can anybody explain this?


回答1:


You have to define $this_id within the function scope, or it'll default to being a global variable. Simply change this:

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

to this:

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

It's a good idea to get into the habit of explicitly declaring all of your variables anyway... Much easier to keep track of them that way.



来源:https://stackoverflow.com/questions/1956698/why-does-a-global-variable-captured-in-a-get-callback-closure-always-hold-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!