Giphy API:使用 jQuery 为随机 GIF 设置新的源属性



我太接近了!还有点困惑...所以告诉我我是否把事情复杂化了。

我正在使用公共 Giphy API 来提取一个随机 gif(下面的示例中的 tag=dog(,并希望在每次单击按钮时循环浏览新 gif。

在下面的示例中,我让控制台记录"成功",我只是不太弄清楚如何将新的随机 URL 设置为源。

任何帮助不胜感激,提前感谢!

.HTML:

<div class="iframe">
  <iframe src="https://giphy.com/embed/26FmRLBRZfpMNwWdy" id="giphy-embed">
  </iframe>
</div>
<button type='button' class="btn btn-default" id="new"> New GIF
</button>

JS/jQuery:

$("#new").click(function () {
  var gif = $('#giphy-embed').attr('src', function(newGIF){ //This is where it will go!
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(response) {
      console.log("success");    //This is what I get, just need to set the new URL as the src
    }, 
    error: function(e) {
      console.log("uh oh");
      }
    });
  });
});

尝试将 iframe src 作为成功函数的一部分进行更新。

$("#new").click(function () {
 //This is where it will go!
  var imgSrc;
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(response) {
      // console.log(response);
      imgSrc = response.data.image_url;
      $("#giphy-embed").attr("src", imgSrc);
      return false;
    }, 
    error: function(e) {
      console.log("uh oh");
      }
    });
});

最新更新