在通过ajax加载dom元素之前触发cycle2.js

时间:2014-03-31 01:56:11

标签: jquery ajax json tumblr jquery-cycle2

我一直在使用tumblr的v1 json api从帖子中获取图片,而且这部分工作得很好。但是,一旦这些图像被放入dom中,我就无法触发循环2插件 - 它似乎太快了。

这是一个工作小提琴:http://jsfiddle.net/orionrush/9XEw2/

鉴于我的例子,任何人都可以指出我正确的方向,为什么这不起作用? 非常感谢

简而言之,我获取图像并将它们放入dom中:

var Tumblr = Tumblr || {};
Tumblr.RecentPhotos = function(el, postsCount, tagged) {
  var apiUrl = "http://2014frames.tumblr.com/api/read/json?callback=?&filter=text&type=photo&num=" + (postsCount || 10) + "&tagged=" + tagged;  
//var apiUrl = "http://" + document.domain + "/api/read/json?callback=?&filter=text&type=photo&num=" + (postsCount || 10)+ "&tagged=" + tagged;

  var renderPosts = function(posts) {
    return $.map($.map(posts, postInfo), renderPost);
  };

  var renderPost = function(post) {
  //return "<div><a href='" + post.url + "' ><img src='" + post.src + "' width='500' data-cycle-title='"+ post.title + "' /><div class='cycle-overlay'>" + post.title + "</div></a></div>";
  return "<div><img src='" + post.src + "' width='100%' data-cycle-title='"+ post.title + "' /><div class='cycle-overlay'>" + post.title + "</div></div>";

  }; 
  var postInfo = function(post) {
  console.log(post.photos[0]);
      return {
        title: post.photos[0]['caption'],
        url: post["url"],
        height: post.photos[0]['height'],
        src: post.photos[0]['photo-url-500']
      };
  };
  return {
    render: function() {
      $.getJSON(apiUrl, function(data) {
        $("<div class='cycle-slideshow composite-example' data-cycle-fx=fadeout data-cycle-timeout=0 data-cycle-loader=wait data-cycle-auto-height=container data-cycle-slides='> div' >").appendTo($(el)).append(renderPosts(data.posts).join("\n"));
      });
      return this;
    }
  }
};

然后使用以下内容触发它:

jQuery(function() { new Tumblr.RecentPhotos(jQuery(".slideshow"),10 ,"news").render(), function(){$(".cycle-slideshow").cycle();} });

2 个答案:

答案 0 :(得分:0)

它需要一些工作,但我相信我已经确定了您的主要问题:如果只有一张照片,则数组photos为空,您需要从其他位置获取有关该照片的信息对象。

见我改变的JS小提琴here

答案 1 :(得分:0)

所以我确实在动态添加到DOM之后找到了触发幻灯片的解决方案。尝试我可能从未找到方法在元素添加到DOM之后触发幻灯片,从同一个脚本中。我的解决方案可能没有最低的开销,但我发现最简单的方法是创建第二个脚本,只需每半秒检查一次新的DOM元素,然后在它们到位后触发滑动的节目。

该触发器看起来像这样:

  setTimeout(function trigger() {
    if ($('.cycle-slideshow').length) {
        $('.cycle-slideshow').cycle({
            timeout: 6000,
            fx: 'fadeout',
            random: true,
            pauseOnHover: true,
            autoHeight: 'calc'
        });
        } else {
            // keep trying until the slideshow elements are added to DOM
            setTimeout(trigger, 50); 
        }
      }, 50);
  });

我的工作小提琴:http://jsfiddle.net/orionrush/pAMLM/

我很想看到其他方法,但这是一个有效的解决方案。