为什么在$ .get()回调关闭中捕获的全局变量始终保持相同的值? [英] Why does a global variable captured in a $.get() callback closure always hold the same value?
问题描述
我在 $。get()
回调中捕获全局变量的值时遇到了一些问题:
相关标记
< div class =blockid =blog>< / div> ;
< div class =blockid =music>< / div>
< div class =blockid =video>< / div>
相关代码
< code $('div.block')。each(function(){
$ this_id = $(this).attr('id');
$ b $ ($ this_id); //输出:博客,音乐,视频
$ .get('test.php',{id:$ this_id},函数(数据){
alert($ this_id); //输出:blog,blog,blog(WHY?)
$('div#'+ $ this_id).html(data);
});
});
我试图获取HTML内容并将其插入到每个 i> divs,但是$ this_id 在调用 $。get()
时没有改变。有人可以解释这一点吗?
您必须在函数范围内定义 $ this_id ,否则它将默认为一个全局变量。简单地改变它:
$ this_id = $(this).attr('id'); b
var $ this_id = $(this).attr('id');
不管怎样,养成显式声明所有变量的习惯是一个好主意......很多更容易跟踪他们。
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?
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.
这篇关于为什么在$ .get()回调关闭中捕获的全局变量始终保持相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!