$ getJSON和for循环问题 [英] $getJSON and for loop issue

查看:162
本文介绍了$ getJSON和for循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用表格填充从MediaWiki API查询返回的结果数量 /api.php?action=query&list=querypage&qppage=BrokenRedirects 。然后将结果数添加到id中,例如:

This is to populate a table with the amount of results that are returned from the MediaWiki API query /api.php?action=query&list=querypage&qppage=BrokenRedirects. The number of results is then added to the id, for example:

// BrokenRedirects
$.getJSON('/api.php?action=query&list=querypage&qppage=BrokenRedirects&format=json', function (data) {
    $('#BrokenRedirects').text(data.query.querypage.results.length);
});

但是,由于它重复了7次,我将qppage的参数变成了一个数组并使用了一个循环缩短整体代码。

But as it's being repeated another 7 times I made the arguments for qppage into an array and used a for loop to shorten overall code.

var array = ['BrokenRedirects',
             'DoubleRedirects',
             'Unusedcategories',
             'Unusedimages',
             'Wantedcategories',
             'Wantedfiles',
             'Wantedpages',
             'Wantedtemplates'];

for (var i = 0; i < array.length; i++) {
    $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
    });
}

第一个未开环的版本有效。但是当我添加一个循环时它没有。 $ getJSON 部分执行,但它无法将结果数据添加到id。我通过JSLint运行它,除了抱怨循环中的函数,并声明 var i var array 返回一点帮助。我对javascript相对缺乏经验,所以想到一个变量不能在循环中使用两次?除此之外,可能与在循环中使用id有关吗?

The first, unlooped, version works. But when I added a loop it didn't. The $getJSON part executes, but it then fails to add the resultant data to the id. I ran it through JSLint which apart from complaining about functions in a loop and declaring var i with var array returned little help. I'm relatively inexperienced with javascript so thought perhaps a variable can't be used twice within a loop? Other than that, maybe something to do with using an id within a loop?

推荐答案

这是一个经典问题: i 在调用回调时具有循环结束的值。

That's a classical problem : i has the value of end of loop when the callback is called.

你可以像这样解决它:

for (var i = 0; i < array.length; i++) {
    (function(i) { // protects i in an immediately called function
      $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
      });
    })(i);
}

2018年附录:

在今天的浏览器中现在有另一个更清洁的解决方案:使用代替 var

There's now another cleaner solution in today's browsers: use let instead of var:

for (let i = 0; i < array.length; i++) {
    $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
    });
}

这篇关于$ getJSON和for循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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