使用Javascript / jQuery的变量不给预期值 [英] Javascript/jQuery variables not giving expected values

查看:123
本文介绍了使用Javascript / jQuery的变量不给预期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像我在别人面前我挣扎与范围在Javascript中。 (这并试图读取该死的东西)。我检查了一些previous线程对这个问题,但我似乎无法让他们正确地应用到我的issuue。 在下面的例子中,我要处理的值 tagsArr 阵列中,一旦阵列已经完全填充。我声明其中填充以全局访问它的功能的范围之外的tagsArr变量。但该变量似乎并不具有范围我希望 - tagsArr.length 0时,我称之为输出到控制台上线16点

  $(函数(){
            VAR apiKey = [myapikey]
            VAR标签='';
            VAR tagsArr =新的Array();
            $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + apiKey +'和; USER_ID = 46206266 @ N05和放大器;群众演员= date_taken,标签和放大器;格式= JSON和放大器; jsoncallback =?',功能(数据){
                $每个(data.photos.photo,功能(I,项目){
                    VAR PHOTOID = item.id;
                    $ .getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key='+ apiKey +'&安培; photo_id ='+ PHOTOID +'&安培;格式= JSON和放大器; jsoncallback =',功能(数据){?
                        如果(data.photo.tags.tag!=''){
                            $每个(data.photo.tags.tag,功能(J,项目){
                                tagsArr.push(item.raw);
                            });
                        }
                    });
                    标签= tagsArr.join('< BR />');
                    console.debug(tagsArr.length);
                });
                $('#总-拖)追加(data.photos.total)。
                $('#类型 - 拖)追加(标签)。
            });
        });
 

解决方案

您拨打的getJSON是异步的。因此,所有的调用内部的getJSON将由console.debug线到达时仍然突出。因此,数组的长度仍然为0。

您需要运行一些额外的code,一旦最终的getJSON调用完成。

  $(函数(){
        VAR apiKey = [myapikey]
        VAR标签='';
        VAR tagsArr =新的Array();
        $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + apiKey +'和; USER_ID = 46206266 @ N05和放大器;群众演员= date_taken,标签和放大器;格式= JSON和放大器; jsoncallback =?',功能(数据){

            VAR totalExpected = data.photos.total;
            变种totalFetched = 0;

            $每个(data.photos.photo,功能(I,项目){
                VAR PHOTOID = item.id;

                $ .getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key='+ apiKey +'&安培; photo_id ='+ PHOTOID +'&安培;格式= JSON和放大器; jsoncallback =',功能(数据){?
                    如果(data.photo.tags.tag!=''){
                        $每个(data.photo.tags.tag,功能(J,项目){
                            tagsArr.push(item.raw);
                            totalFetched + = 1;
                            如果(totalFetched == totalExpected)
                              fetchComplete();
                        });
                    }
                });
                功能fetchComplete()
                {
                    标签= tagsArr.join('< BR />');
                    console.debug(tagsArr.length);
                }
            });
            $('#总-拖)追加(data.photos.total)。
            $('#类型 - 拖)追加(标签)。
        });
    });
 

此假设作品的照片总数不excede每页默认100,其他明智的,你需要调整它。

这是说,我不认为使用。每到断火的getJSON请求的负荷,使一个很大的意义。我会重构它,这样只有一个的getJSON调用突出在任何一个时间。有一个问题在未来的getJSON下一张照片,直到一切都被拉到则回调做你完成code。

Like others before me I'm struggling with scope in Javascript. (That and trying to read the darn stuff). I have checked some of the previous threads on this question but I cant seem to get them to apply correctly to my issuue. In the example below, I want to manipulate the values in the tagsArr array, once the array has been fully populated. I declared the tagsArr variable outside the scope of the function in which it is populated in order to access it globally. But the variable doesn't seem to have the scope I expect - tagsArr.length is 0 at the point where I call output it to console on line 16.

            $(function(){
            var apiKey = [myapikey];
            var tags = '';
            var tagsArr = new Array();
            $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + apiKey + '&user_id=46206266@N05&extras=date_taken,tags&format=json&jsoncallback=?', function(data){
                $.each(data.photos.photo, function(i, item) {
                    var photoID = item.id;
                    $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?', function(data){
                        if (data.photo.tags.tag != '') {
                            $.each(data.photo.tags.tag, function(j, item) {
                                tagsArr.push(item.raw);
                            });
                        }                            
                    });
                    tags = tagsArr.join('<br />');
                    console.debug(tagsArr.length);
                });
                $('#total-dragged').append(data.photos.total);
                $('#types-dragged').append(tags);
            });
        });

解决方案

Your calls to getJSON are asynchronous. Hence all the calls to the inner getJSON will still be outstanding by the time the console.debug line is reached. Hence the array length is still 0.

You need to run some extra code once the final getJSON call has completed.

        $(function(){ 
        var apiKey = [myapikey]; 
        var tags = ''; 
        var tagsArr = new Array(); 
        $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + apiKey + '&user_id=46206266@N05&extras=date_taken,tags&format=json&jsoncallback=?', function(data){

            var totalExpected = data.photos.total;
            var totalFetched = 0;

            $.each(data.photos.photo, function(i, item) { 
                var photoID = item.id;

                $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?', function(data){ 
                    if (data.photo.tags.tag != '') { 
                        $.each(data.photo.tags.tag, function(j, item) { 
                            tagsArr.push(item.raw);
                            totalFetched += 1;
                            if (totalFetched == totalExpected)
                              fetchComplete();
                        }); 
                    }                             
                });
                function fetchComplete()
                { 
                    tags = tagsArr.join('<br />'); 
                    console.debug(tagsArr.length); 
                }
            }); 
            $('#total-dragged').append(data.photos.total); 
            $('#types-dragged').append(tags); 
        }); 
    });

This works assuming the total number of photos doesn't excede the default 100 per page, other wise you would need to tweak it.

That said I don't think using .each to fire off loads of getJSON requests makes a great deal of sense. I would refactor it so that only one call to getJSON is outstanding at any one time. Have the callback of one issue the next getJSON for the next photo until all have been pulled then do your completed code.

这篇关于使用Javascript / jQuery的变量不给预期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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