简体   繁体   English

jQuery将参数传递给$ .get()回调函数

[英]jQuery pass argument to $.get() callback function

I am using this piece of code to retrieve some JSONs from twitch: 我正在使用这段代码从twitch检索一些JSON:

for (var i = 0; i < streamList.length; i++) {
     $.get(baseURL + streamList[i], getStreamInfo, "json");
}  

where getStreamInfo is the callback function. 其中getStreamInfo是回调函数。 I would like to know if it is possible to pass the value of "i" to the callback function somehow, along with the JSON. 我想知道是否可以将“ i”的值与JSON一起传递给回调函数。

Yes, you can pass the default parameter that receive the data of the ajax query and then add the i var. 是的,您可以传递接收Ajax查询数据的默认参数,然后添加i var。

 for (var i = 0; i < streamList.length; i++) {
     $.get(baseURL + streamList[i],
           function(data) { getStreamInfo(data, i) }, 
           "json");
 } 

Note that you need to receive it in getStreamInfo function 请注意,您需要在getStreamInfo函数中接收它

Hope it helps. 希望能帮助到你。

You can add any variables you want to the anonymous object. 您可以将所需的任何变量添加到匿名对象。 Be sure those variables are not used by the get function. 确保get函数未使用这些变量。 For exemple, I added the variable foo to the anonymous object and used it with this.foo in the callback function : 例如,我将变量foo添加到匿名对象中,并将其与回调函数中的this.foo一起使用:

for (var i = 0; i < streamList.length; i++) {
    $.get({
      url: baseURL + streamList[i],
      success: getStreamInfo,
      dataType: "json",
      foo:i
    });
} 

function getStreamInfo()
{
    var i = this.foo;
}

You can use Closures . 您可以使用Closures

for (var i = 0; i < streamList.length; i++) {
    (function(index){
        $.get(baseURL + streamList[i], function(data){
            getStreamInfo(data, index);
        }, "json");
    })(i);     
} 

Note: Modify your function getStreamInfo to accept index . 注意:修改您的函数getStreamInfo以接受index

Read How do JavaScript closures work? 阅读JavaScript闭包如何工作?

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

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