cuốn sách gpt4 ai đã làm

javascript - jQuery 中 getJSON 的范围

In lại Tác giả: Walker 123 更新时间:2023-11-28 21:18:48 25 4
mua khóa gpt4 Nike

在使用 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
    });
    });
    }

    目前,我必须将轮播功能放置在 getJSON 函数中。如果我创建另一个函数来设置轮播,我就会失去 getJSON 中的范围。

    解决这个问题的首选方法是什么,这样我就可以得到 setupCarousel : function()是从 getJSON 调用的吗?通常,如果我想从对象中的另一个函数调用函数,我可以直接输入 this.setupCarousel() ,但是对于嵌套范围,我不确定如何处理这个问题。

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

    câu trả lời hay nhất

    $.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('
  • ' + v.bar + '
  • ');
    }
    cb(items);
    });
    }

    //...

    thing.grabJSON(buildCarousel);

    如果您想将 $.getJSON 与需要对该 JSON 执行的操作分开。在这种特殊情况下,像上面那样将其分解比实际工作更繁忙,但在处理 AJAX 时,这种模式(回调中的回调,一直向下的回调)非常常见。

    关于javascript - jQuery 中 getJSON 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6922237/

    25 4 0
    Chứng chỉ ICP Bắc Kinh số 000000
    Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
    Xem sitemap của VNExpress