简体   繁体   English

jQuery将变量从一个函数传递到另一个函数

[英]jQuery Passing Variable from From One Function to Another Function

I need to create a variable and assign a value to this variable to use later on. 我需要创建一个变量并为此变量赋值以便稍后使用。 To save complexity and keep it simple, I've removed details that are also part of what else goes into var item2. 为了节省复杂性并保持简单,我删除了细节,这些细节也是var item2的其他部分。 The variable in this example would be mySeries 此示例中的变量是mySeries

var mySeries;

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
//Stuff happens here

//NEED TO ASSIGN VALUE TO mySeries HERE:
mySeries = item[0].series_id;

//Stuff happens here
});

//NEED TO USER mySeries VALUE HERE BUT IT IS NOT DEFINED
var item2 = mySeries;

With ajax you need to use callbacks since ajax is asynchronous : 使用ajax,您需要使用回调,因为ajax是asynchronous

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
   var mySeries;
   //Stuff happens here

   //NEED TO ASSIGN VALUE TO mySeries HERE:
   mySeries = item[0].series_id;
   save_series(mySeries)
   //Stuff happens here
});

function save_series(s){

   var item2 = mySeries;

   //...etc
}

在json请求完成后,mySeries get被分配,你的item2在完成之前被分配。

Yeah I think you need a setter for the item2 since it's happening after the function but since it's asynchronous it's not going to have a value until it returns. 是的,我认为你需要一个set2的setter,因为它发生在函数之后,但由于它是异步的,所以在它返回之前它不会有值。 You could also use .ajax() and set the function to synchronous if you need that kind of functionality. 如果需要这种功能,也可以使用.ajax()并将函数设置为同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM