jQuery全局变量问题 [英] jQuery global variable problem

查看:138
本文介绍了jQuery全局变量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var id = $(this).children()。html(); // id是5 
$ .ajax({
url:'ajax.php?id ='+ id,
success:function(data){
id = data; // id是1
}
});
if(id == 1){// id is again 5
...
}

为什么在下面的例子中,我不能重新初始化id变量?什么是错误的?



谢谢。 <$ c < $ c> $。ajax()函数必须去获取数据,它没有做到这一点,并执行成功回调到它后立即到达代码。



您的代码顺序实际上是这样发生的:

  var id = $(this)。 。儿童()HTML(); 
// Ajax start $ b $ if if(id == 1){}
// Ajax结束(稍后,不是之后)
函数(data){id = data; }

如果您要继续使用此值,请将其保留在成功回调中:

  var id = $(this).children()。html(); // id是5 
$ .ajax({
url:'ajax.php?id ='+ id,
success:function(data){
id = data; // id是1
if(id == 1){// id is now 1
...
}
}
});


var id = $(this).children().html();  // id is 5
$.ajax({
   url: 'ajax.php?id=' + id,
   success: function(data) {
      id = data;   // id is 1
   }
});
if(id == 1){    // id is again 5
   ...
}

Why in the following example I can't reinitialize the id variable? What is wrong?

Thanks.

解决方案

The $.ajax() function has to go and get the data, it hasn't done this and executed your success callback by the time it reached the code immediately after.

Your code order actually happens like this:

var id = $(this).children().html();
//Ajax start
if(id == 1){ }
//Ajax end (sometime later, not immediately after)
function(data) { id = data; }

If you are depending on this value to continue, stick it in the success callback:

var id = $(this).children().html();  // id is 5
$.ajax({
   url: 'ajax.php?id=' + id,
   success: function(data) {
      id = data;   // id is 1
      if(id == 1){    // id is now 1
        ...
      }
   }
});

这篇关于jQuery全局变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆