簡體   English   中英

jQuery中getJSON的范圍

[英]Scope for getJSON in jQuery

使用getJSON時嘗試管理范圍時遇到麻煩。
因此,在HTML頁面上,我有一個無序列表,要填充一個JSON文件中的列表項。 該列表是輪播的標記。

HTML:
<ul class="carousel"></ul>

JS:

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

當前,我必須將輪播函數放置在getJSON函數中。 如果我使用另一個函數來設置輪播,則會丟失getJSON中的范圍。

什么是實現此目的的首選方法,這樣我就可以從setupCarousel : function() 通常,如果我想從對象中的另一個函數調用一個函數,則可以轉到this.setupCarousel() ,但是對於嵌套范圍,我不確定該如何處理。

另外,在getJSON函數之外,我無權訪問任何附加的元素。 因此,我可以訪問ul,但不能訪問從getJSON添加它們時創建的所有列表項。

$.getJSON調用是異步的。 因此,如果您這樣做:

thing.grabJSON();
do_some_other_stuff();

do_some_other_stuff將在$.getJSON調用完成之前執行。 您必須將所有內容都放入$.getJSON回調中,因為該代碼段將在將來的某個時間執行。 回調可以自由地將接收到的任何數據傳遞給其他函數(如Kishnore的回答),但是在$.getJSON 之后執行的代碼(源代碼中after之后)不能依賴$.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('<li>' + v.bar + '</li>');
        }
        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('<li>' + v.bar + '</li>');
        }
        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
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM