如何在 JQuery $.each 函数中编辑全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:20:39  来源:igfitidea点击:

How do I edit a global variable in a JQuery $.each function?

jqueryjsonglobal-variablesscope

提问by bryan

Ok, so that title probably doesn't explain my question well. Hopefully this makes sense. This is also my first application with jQuery, so forgive me if I'm doing something dumb.

好的,所以这个标题可能不能很好地解释我的问题。希望这是有道理的。这也是我第一个使用 jQuery 的应用程序,所以如果我做了一些愚蠢的事情,请原谅我。

I have the following function:

我有以下功能:

function getRandomImages(limit) {
    imagesArray = new Array();
    $.getJSON('createImageArray.php', {limit: limit}, function(data) {
        $.each(data, function(i) {
            imagesArray[i] = data[i];  //imagesArray is declared globally.
        });
    }); 
}

The getJSON is correctly grabbing the JSON object. It returns something like this:

getJSON 正确抓取了 JSON 对象。它返回如下内容:

{"image0":"images/19.10.FBB9.jpg","image1":"images/8.16.94070.jpg","image2":"images/8.14.47683.jpg","image3":"images/8.15.99404.jpg","image4":"images/8.13.20680.jpg","image5":"images/21.12.9A.jpg","image6":"images/8.17.75303.jpg"}

I was debugging and am confident that data[i] correctly contains the image path as grabbed from the JSON object. However, after getRandomImages() is called, I look at my global imagesArray and notice that nothing has been changed. I'm guessing it's creating a copy of the imagesArray instead of grabbing the actual one.

我正在调试并且确信 data[i] 正确包含从 JSON 对象中获取的图像路径。但是,在调用 getRandomImages() 之后,我查看了全局 imagesArray 并注意到没有任何更改。我猜它正在创建 imagesArray 的副本,而不是抓取实际的副本。

Can someone tell me what I need to do so that my global imagesArray gets updated in the $.each block? Do I need to pass in imagesArray by reference somehow? Sorry, I'm a bit lost.

有人能告诉我我需要做什么才能在 $.each 块中更新我的全局 imagesArray 吗?我需要以某种方式通过引用传入 imagesArray 吗?对不起,我有点失落。

Thanks for the help.

谢谢您的帮助。

EDIT: Some background information. I am populating an array of random image locations from the DB. I don't want to load all the images from the db to an array at once, because there are just too many. So, I have a counter which keeps track of where I am in my image array. Once I'm done with an image, I move the pointer to the next image. If I reach the end, I need to grab more random images. That's where the above js function gets called; it calls createImageArray.php which grabs x random images from the db and returns an array. I then want to store those image locations in my global imagesArray.

编辑:一些背景信息。我正在从数据库填充一组随机图像位置。我不想一次将所有图像从数据库加载到数组中,因为太多了。所以,我有一个计数器来跟踪我在图像数组中的位置。完成图像后,我将指针移动到下一个图像。如果我到达终点,我需要抓取更多随机图像。这就是上面 js 函数被调用的地方;它调用 createImageArray.php 从数据库中抓取 x 个随机图像并返回一个数组。然后我想将这些图像位置存储在我的全局 imagesArray 中。

I'm not sure how I would restructure my code to take .getJSON's asynchronouos nature into account.

我不确定我将如何重组我的代码以将 .getJSON 的异步性质考虑在内。

回答by kgiannakakis

What happens here is that the getJSONis called asynchronously. So the function returns immediately and the code inside it is called at some point later at time. It was only then that the imagesArray would be updated.

这里发生的getJSON是异步调用。因此该函数立即返回,并在稍后的某个时间点调用其中的代码。只有在那时,imagesArray 才会被更新。

You could have the getJSON behave synchronously, but I wouldn't recommend it. Instead I recommend restructuring your code to take into consideration the asynchronous nature of AJAX requests.

您可以让 getJSON 同步运行,但我不建议这样做。相反,我建议重构您的代码以考虑 AJAX 请求的异步性质。

EDIT:For making a synchronous request use the asyncoption (link). Use the general $.ajaxfunction or set AJAX global options. The reason that I don't recommend this is, that it locks the browser. If your server fails to respond in a timely fashion, the user will not be able to use his/her browser.

编辑:要发出同步请求,请使用async选项(链接)。使用通用$.ajax函数或设置 AJAX 全局选项。我不建议这样做的原因是,它会锁定浏览器。如果您的服务器未能及时响应,用户将无法使用他/她的浏览器。

It isn't that difficult to restructure your code. Just move your logic for handling image arrays in the callback function. For example instead of:

重构代码并不难。只需在回调函数中移动处理图像数组的逻辑即可。例如,而不是:

function getRandomImages(limit) {
    imagesArray = new Array();
    $.getJSON('createImageArray.php', {limit: limit}, function(data) {
        $.each(data, function(i) {
                imagesArray[i] = data[i];  //imagesArray is declared globally.
        });
    }); 
   processImages();
}

do

function getRandomImages(limit) {
    imagesArray = new Array();
    $.getJSON('createImageArray.php', {limit: limit}, function(data) {
        $.each(data, function(i) {
                imagesArray[i] = data[i];  //imagesArray is declared globally.
        });
        processImages();
    }); 
}

回答by defrex

Alright, I didn't understand the problem the first time. It's a little hackey, but without knowing more about your code I'd say when you create your imagesArray create a bool imagesLoaded.

好吧,我第一次没明白这个问题。这有点hackey,但在不了解您的代码的情况下,我会说当您创建imagesArray 时创建一个bool imagesLoaded。

function getRandomImages(limit) {
    imagesArray = new Array();
    imagesLoaded = false;
    $.getJSON('createImageArray.php', {limit: limit}, function(data) {
        $.each(data, function(i) {
                imagesArray[i] = data[i];  //imagesArray is declared globally.
        });
        imagesLoaded = true;
    }); 
}

Then, after you call getRandomImages() put your code into a holding pattern with setTimeout() until imagesLoaded = true. Oh, and maybe put some kind of loading graphic on the page for the user to look at so they don't think your app is busted.

然后,在您调用 getRandomImages() 之后,使用 setTimeout() 将您的代码放入保持模式,直到 imagesLoaded = true。哦,也许可以在页面上放一些加载图形供用户查看,这样他们就不会认为您的应用程序被破坏了。

回答by defrex

try this:

尝试这个:

function getRandomImages(limit) {
    imagesArray = new Array();
    $.getJSON('createImageArray.php', {limit: limit}, function(data) {
        $.each(data, function(i, val) {
                imagesArray[i] = val;  //imagesArray is declared globally.
        });
    }); 
}

回答by Tim Büthe

First of all: Why you are using a global variable? That's a bad idea, don't do it. You can share variables between functions within a given namespace like this:

首先:为什么要使用全局变量?这是个坏主意,不要这样做。您可以在给定命名空间内的函数之间共享变量,如下所示:

var NAMESPACE = {};
NAMESPACE.example = function() { 

    var myField = '1';

    return { 

        someMethod: function() { 
             return myField;
        }, 

        anotherMethod: function() { 
            return myField;
        } 
    };
}();

Secondly, what do you do after the array is fetched? Do you want to display the images on the page or something? Could you at the img-elements to the page instead of putting them into the array?

其次,获取到数组之后怎么办?你想在页面上显示图像还是什么?您可以将 img-elements 放入页面而不是将它们放入数组中吗?

回答by Alexander

maybe this work, works to me.. :)

也许这项工作,对我有用.. :)

$variable= new array();

$.getJSON("url", function(data){
asignVariable(data);
}

function asignVariable(data){
$variable = data;
}

console.log($variable);

Hope it help you.. :)

希望对你有帮助.. :)