Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数闭包中的javascript函数闭包_Javascript_Function_Nested_Closures_Getjson - Fatal编程技术网

函数闭包中的javascript函数闭包

函数闭包中的javascript函数闭包,javascript,function,nested,closures,getjson,Javascript,Function,Nested,Closures,Getjson,我在以下代码中遇到此问题: var feedurl=”https://itunes.apple.com/nl/rss/topsongs/limit=25/xml"; 变量j,i,x; $.getJSON(“http://ajax.googleapis.com/ajax/services/feed/load?q=“+feedurl+”&v=1.0&num=-1&callback=?”,函数(数据){ 对于(j=0;j

我在以下代码中遇到此问题:

var feedurl=”https://itunes.apple.com/nl/rss/topsongs/limit=25/xml";
变量j,i,x;
$.getJSON(“http://ajax.googleapis.com/ajax/services/feed/load?q=“+feedurl+”&v=1.0&num=-1&callback=?”,函数(数据){
对于(j=0;j<21;j+=1){
qt=j+“+data.responseData.feed.entries[j].title.replace('#','');
控制台日志(qt);
li=$(“
  • ”)html(qt).appendTo(“#ul1”); $.getJSON(“http://gdata.youtube.com/feeds/api/videos?q=“+qt+”&v=2&start index=1&max results=1&orderby=relevance&format=5&alt=jsonc&callback=?”,(函数(el){ 返回功能(视频馈送){ 对于(i=0;i”); el.append(newdiv); } }; }(李),; } })
  • 它需要做的是:

  • 从RSS源获取标题(works)
  • 将它们(最多20个)放入无序列表中-按编号(工程)排序的注释
  • 在youtube api上搜索每个标题一个漂亮的视频(works)
  • 在创建的li(作品)中输入一些信息(YID是可以的,标题也是可以的)
  • 它需要从外部/母函数中获取变量qt才能使用它。 但是-它总是获取行中最后一个填充的qt变量
  • 我不明白为什么,我想我需要和另一次关闭有关。 但不确定。 我在互联网上到处搜索,但没有任何线索


    感谢您的帮助。

    现在发生的事情是,qt引用在外部循环的每次迭代中都会被更新,当对Youtube API的第一个Ajax响应完成时,外部循环已经结束

    您必须将每个qt引用与每个内部Ajax请求一起存储,以便请求将更新相关LI

    最简单的方法是创建一个函数,该函数返回一个使用外部函数参数的函数:

    var renderLi = function (qt, el) {
        return function(videoFeed) {
            ...
        };
    };
    
    ...
    
    $.getJSON("http://gdata.youtube.com/feeds/api/videos?q=" + qt + "&v=2&start-index=1&max-results=1&orderby=relevance&format=5&alt=jsonc&callback=?", renderLi(qt, li));
    

    很好的解释和解决方案!
    var renderLi = function (qt, el) {
        return function(videoFeed) {
            ...
        };
    };
    
    ...
    
    $.getJSON("http://gdata.youtube.com/feeds/api/videos?q=" + qt + "&v=2&start-index=1&max-results=1&orderby=relevance&format=5&alt=jsonc&callback=?", renderLi(qt, li));