【问题标题】:Owl carousel 2 not working after api callapi调用后猫头鹰轮播2不工作
【发布时间】:2020-02-04 22:45:05
【问题描述】:

我正在从 youtube API 获取一些数据,但是当我使用以下代码时。猫头鹰旋转木马不工作。

var url = "https://www.googleapis.com/youtube/v3/videos?part=statistics,contentDetails&id=" + get_video_id + "&key=" + api_key + "";
$.get(url, function(value) {

    if (value.items[0] != undefined) {
        var video_viewers = value.items[0].statistics.viewCount;
        single_carousel_container.append('<div class="single-video"><h3 class="video-view">' + video_viewers + '</h3>/div>');

    }
});
owl_active();

function owl_active() {
    single_carousel_container.owlCarousel({
            loop: true,
            margin: 30,
        }
    });
}

但是,如果我删除了 api 调用,那么 owl carousel 就会正常工作。那么我如何在 youtube api 调用中使用 owl carousel 2 呢?

完整源代码:https://pastebin.com/bKeLYbZv

【问题讨论】:

  • $.get 调用是异步的。您正在尝试在加载之前激活。将owl_active() 放入if 语句中。
  • 是的..我可以在 $.get 中使用它,但是在该语句之外还有另一个 $.get 来获取其他一些 api 数据 + 在 .each 函数中。完整代码:pastebin.com/bKeLYbZv

标签: javascript api youtube-api owl-carousel owl-carousel-2


【解决方案1】:

修改滑块的 HTML 后(通过 prepend、append 等),您需要让 OwlCarousel 知道 HTML 已被修改,触发 carousel 元素上的 refresh.owl.carousel 事件。

不要与refreshed.owl.carousel 事件混淆,该事件会在您的滑块更新后自动触发。

文档:https://owlcarousel2.github.io/OwlCarousel2/docs/api-events.html#refresh-owl-carousel

【讨论】:

【解决方案2】:

在数据获取完成并附加到容器之前,您正在初始化 owl carousel。

var url = "https://www.googleapis.com/youtube/v3/videos?part=statistics,contentDetails&id=" + get_video_id + "&key=" + api_key + "";

function owl_active() {
    single_carousel_container.owlCarousel({
            loop: true,
            margin: 30,
        }
    });
}

$.get(url, function(value) {

    if (value.items[0] != undefined) {
        var video_viewers = value.items[0].statistics.viewCount;
        single_carousel_container.append('<div class="single-video"><h3 class="video-view">' + video_viewers + '</h3>/div>');
        owl_active();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2023-03-29
    相关资源
    最近更新 更多