全局变量的JavaScript范围问题

时间:2014-04-19 10:16:17

标签: javascript jquery

我需要获取视频的视图数量(video.numviews),以便我可以填充另一个脚本来制作图形。我的全局变量视频如下所示:

var video = 
$(function(){
    $('#usersnav ul li a').on('click', function(e){
        e.preventDefault();
        var htmlString  = '<ul id="videoslisting">';
        var channelname = $(this).attr('href').substring(1);
        var ytapiurl    = 'http://gdata.youtube.com/feeds/api/users/'+channelname+'/uploads?alt=json&max-results=10';

        $.getJSON(ytapiurl, function(data) {
            $.each(data.feed.entry, function(i, item) {
                var title    = item['title']['$t'];
                var videoid  = item['id']['$t'];

                var pubdate  = item['published']['$t'];
                var fulldate = new Date(pubdate).toLocaleDateString();

                var thumbimg = item['media$group']['media$thumbnail'][0]['url'];
                var tinyimg1 = item['media$group']['media$thumbnail'][1]['url'];
                var tinyimg2 = item['media$group']['media$thumbnail'][2]['url'];
                var tinyimg3 = item['media$group']['media$thumbnail'][3]['url'];

                var vlink    = item['media$group']['media$content'][0]['url'];
                var ytlink   = item['media$group']['media$player'][0]['url'];
                var numviews = item['yt$statistics']['viewCount'];
                var numcomms = item['gd$comments']['gd$feedLink']['countHint'];

                htmlString +='<li class="clearfix"><h2>' + title + '</h2>';
                htmlString +='<div class="videothumb"><a href="' + ytlink + '" target="_blank"><img src="' + thumbimg + '" width="480" height="360"></a></div>';
                htmlString +='<div class="meta"><p>Published on <strong>' + fulldate + '</strong></p><p>Total views: <strong>' + commafy(numviews) + '</strong></p>' +
                    '<p>Total comments: <strong>'+ numcomms +'</strong></p>' +
                    '<p><a href="'+ ytlink +'" class="external" target="_blank">View on YouTube</a></p>' +
                    '<p><a href="'+ vlink +'" class="external" target="_blank">View in Fullscreen</a></p>';
                // hiding the alt thumbnails
                //+
                //'<p><strong>Alternate Thumbnails</strong>:<br><img src="'+ tinyimg1 +'"> ' +
                //'<img src="' + tinyimg2 + '"> <img src="'+ tinyimg3 +'"></p></div></li>';
            }); // end each loop

            $('#videos').html(htmlString + "</ul>");
});

然后我需要在下面的代码中使用video.numviews,它存储在与上面代码不同的文件中:

    // code for chart display
var videoChart = video.numviews;

        //Get context with jQuery - using jQuery's .get() method.
         var ctx = $("#myChart").get(0).getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx);
    {

    for (var i=0; i<videoChart.length; i++);


        var data = [

            {
                value: i,
                color:"#F38630"
            },
            {
                value : i,
                color : "#E0E4CC"
            },
            {
                value : i,
                color : "#69D2E7"
            }
        ];
    }
    var options = {
        scaleFontColor: "#f00",
        datasetStrokeWidth: 20
    };

    new Chart(ctx).Pie(data,options);

似乎有一个范围问题,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要使视频变量像您一样全局化,但不要将其分配给document.ready函数。相反,你可以

//var video = {}; //Will only "collect' the last value as its being reassigned every loop cycle. 
var video = []; //To get all the values through the $.each loop

$(function(){
    $('#usersnav ul li a').on('click', function(e){
        e.preventDefault();
        var htmlString  = '<ul id="videoslisting">';
        var channelname = $(this).attr('href').substring(1);
        var ytapiurl    = 'http://gdata.youtube.com/feeds/api/users/'+channelname+'/uploads?alt=json&max-results=10';

        $.getJSON(ytapiurl, function(data) {
            $.each(data.feed.entry, function(i, item) {
                var title    = item['title']['$t'];
                var videoid  = item['id']['$t'];

                var pubdate  = item['published']['$t'];
                var fulldate = new Date(pubdate).toLocaleDateString();

                var thumbimg = item['media$group']['media$thumbnail'][0]['url'];
                var tinyimg1 = item['media$group']['media$thumbnail'][1]['url'];
                var tinyimg2 = item['media$group']['media$thumbnail'][2]['url'];
                var tinyimg3 = item['media$group']['media$thumbnail'][3]['url'];

                var vlink    = item['media$group']['media$content'][0]['url'];
                var ytlink   = item['media$group']['media$player'][0]['url'];
                var numviews = item['yt$statistics']['viewCount'];
                var numcomms = item['gd$comments']['gd$feedLink']['countHint'];

                htmlString +='<li class="clearfix"><h2>' + title + '</h2>';
                htmlString +='<div class="videothumb"><a href="' + ytlink + '" target="_blank"><img src="' + thumbimg + '" width="480" height="360"></a></div>';
                htmlString +='<div class="meta"><p>Published on <strong>' + fulldate + '</strong></p><p>Total views: <strong>' + commafy(numviews) + '</strong></p>' +
                    '<p>Total comments: <strong>'+ numcomms +'</strong></p>' +
                    '<p><a href="'+ ytlink +'" class="external" target="_blank">View on YouTube</a></p>' +
                    '<p><a href="'+ vlink +'" class="external" target="_blank">View in Fullscreen</a></p>';
                // hiding the alt thumbnails
                //+
                //'<p><strong>Alternate Thumbnails</strong>:<br><img src="'+ tinyimg1 +'"> ' +
                //'<img src="' + tinyimg2 + '"> <img src="'+ tinyimg3 +'"></p></div></li>';
                //video.numviews = numviews;
                video.push(numviews);

            }); // end each loop

            $('#videos').html(htmlString + "</ul>");

});

请记住,numviews将采用您正在运行的每个循环的最后一个值。它可以设置视频对象,使其成为一个数组,我们将值推送到而不是这个。

在我看来,代码可以清理得更多,但这应该可以解决您的范围问题......

第二部分:

// code for chart display
var videoChart = video; //Not necessary to reassign the value. 

    //Get context with jQuery - using jQuery's .get() method.
     var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
{

for (var i=0; i<videoChart.length; i++);


    var data = [

        {
            value: i,
            color:"#F38630"
        },
        {
            value : i,
            color : "#E0E4CC"
        },
        {
            value : i,
            color : "#69D2E7"
        }
    ];
}
var options = {
    scaleFontColor: "#f00",
    datasetStrokeWidth: 20
};

new Chart(ctx).Pie(data,options);