在jQuery.post中,如何获取函数外部变量的值? [英] In jQuery.post, how do I get value of variable outside function?

查看:476
本文介绍了在jQuery.post中,如何获取函数外部变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能:

var id = "10";
var type = "Type A";
var img = "myimage.jpg";

jQuery.post("my/path/somefile.php", { instance: 'getUrl', ID : id, type: type},
function(data)
{ 
    jQuery('#logo').attr("src",data.url + img);
},"json"); 

  1. 在函数内部时如何获取img的值?
  2. 如何在函数内部设置img = new value?
  1. How can I get the value of img when I'm inside the function?
  2. How can I sett img = new value from inside the function?

更新

此代码未给变量赋予新值:

This code does NOT give a new value to the variable:

    logoUrl = "noLogo.png";

    jQuery.post("my/path/somefile.php", { instance: 'getUrl', ownerID : "123", type: "brand"},
    function(logo)
    {
        logoUrl = logo.url + "logo/";
    },"json");      

    alert(logoUrl); // This outputs noLogo.png"

推荐答案

更新

在使用回调函数时,重要的是要注意执行流程:

When working with callback functions, its important to pay attention to execution flow:

var img = "nice.jpg";

$.post('/path', { key: value }, function(data){
   img = "newname.jpg";
});

alert(img); // Alerts "nice.jpg"

这是因为在回调(而不是在回调函数中)之后发生的所有代码都将首先执行:

It is because any code occurring after the callback (but not in the callback function) is executed first:

  1. img设置为nice.jpg
  2. 致电$.post
  3. 致电alert
  4. img设置为newname.jpg
  1. Set img to nice.jpg
  2. Call $.post
  3. Call alert
  4. Set img to newname.jpg

原始答案:

如果您使用的代码与您发布的代码完全相同,则:

If the code you are using exists exactly as you posted it, then:

  1. img在匿名回调函数中已经可用.
  2. 是的,您也可以在函数内部更改img的值.
  1. img is already available inside your anonymous callback function.
  2. Yes, you can change the value of img from inside the function as well.

使用var关键字声明变量时,该变量是其当前范围的私有变量,但可用于其范围内的任何其他上下文:

When you declare variable with the var keyword, it is private to its current scope, but is available to any other contexts contained within its scope:

作品

function getPost(){
   var img = "nice.jpg";

   $.post('/path', {key:value}, function(data){
       alert(img); // alerts "nice.jpg"
   });
}

不起作用

function changeImage(){
   var img = "nice.jpg";
   getPost();
}

function getPost(){
   $.post('/path', {key:value}, function(data){
       alert(img); // img is undefined
   });
}   

这篇关于在jQuery.post中,如何获取函数外部变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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