jQuery中getJSON的范围

在使用getJSON时,我在尝试管理范围时遇到了一些麻烦。
因此,在HTML页面上,我有一个无序列表,用于填充JSON文件中的列表项。 该列表是旋转木马的标记。

HTML:

JS:

 grabJSON : function() { $.getJSON('file.json', function(data) { var items = []; $.each(data.foo, function(k, v) { items.push('
  • ' + v.bar + '
  • '); } $('ul.carousel').append(items.join('')); // carousel action here $('ul.carousel').carouselFunction({ // carousel options here }); }); }

    目前,我必须将carousel函数放在getJSON函数中。 如果我设置另一个function来设置轮播,我将失去getJSON中的范围。

    什么是打破这个的首选方法,所以我可以有一个从getJSON调用的setupCarousel : function() ? 通常,如果我想从对象中的另一个函数调用一个函数,我可以去this.setupCarousel() ,但是对于嵌套作用域,我不知道如何处理它。

    此外,在getJSON函数之外,我无权访问任何附加的元素。 所以我可以访问ul,但不能访问从getJSON添加它们时创建的任何列表项。

    $.getJSON调用是异步的。 所以,如果你这样做:

     thing.grabJSON(); do_some_other_stuff(); 

    do_some_other_stuff将在$.getJSON调用完成之前执行。 你必须将所有内容放在$.getJSON回调中,因为这段代码将在未来的某个时间执行; 回调可以自由地将它接收的任何数据传递给其他函数(如Kishnore的答案),但是在$.getJSON 之后执行的代码(在源代码之后的意思之后)不能依赖$.getJSON调用做任何事情。

    你可以这样做:

     function buildCarousel(items) { $('ul.carousel').append(items.join('')); $('ul.carousel').carouselFunction({ // carousel options here }); } // ... grabJSON : function(cb) { $.getJSON('file.json', function(data) { var items = []; $.each(data.foo, function(k, v) { items.push('
  • ' + v.bar + '
  • '); } cb(items); }); } //... thing.grabJSON(buildCarousel);

    如果你想将$.getJSON与需要用JSON完成的东西分开。 在这种特殊情况下,像上面那样分开它比实际工作更繁忙,但是这种模式(回调中的回调,回调一直向下)在处理AJAX时非常常见。

    你尝试过这样的事吗?

     grabJSON : function() { $.getJSON('file.json', function(data) { var items = []; $.each(data.foo, function(k, v) { items.push('
  • ' + v.bar + '
  • '); } makeCarousel(items); }); } //pass items to make carosuel function and use it this should solve your problem. makeCarosuel: function(items) { $('ul.carousel').append(items.join('')); // carousel action here $('ul.carousel').carouselFunction({ // carousel options here }); }