【问题标题】:For in loop is showing the img tag instead of the actualy Giphy gifFor in 循环显示 img 标签而不是实际的 Giphy gif
【发布时间】:2019-09-03 15:20:43
【问题描述】:

我正在尝试制作一个 giphy 克隆,我想展示目前流行的六个 gif。但是,当我运行代码时,它似乎可以从响应数据中获取图像源但实际 gif 没有显示。

我尝试使用响应数据中提供的一些不同的 url 和 mp4 链接,但最终总是只显示图像标签。

function getTrending() {

  // Create AJAX request to get the trending gifs

  // Create the new XHR object

  let xhr = new XMLHttpRequest();

  // Call the open function with a GET-type request, url, and set async to true

  xhr.open('GET', 'http://api.giphy.com/v1/gifs/trending?&api_key=<MyApiKey>&limit=6', true);

  // Call the onload function

  xhr.onload = function() {
    // Check if the server status is 200
    if(this.status === 200) {
      // Return server response as an object using JSON.parse
      let trendingResponse = JSON.parse(this.responseText);

      // Create for in loop to insert the trending gifs into the gif container div

      for (i in trendingResponse.data) {
        gifsContainer.append("<img src='"+ trendingResponse.data[i].images.original.url+"' />")
      }

      console.log(trendingResponse.data[1]);
    }
  }

【问题讨论】:

    标签: javascript api giphy-api


    【解决方案1】:

    这是因为当您使用append() 时,实际上是在将实际文本而不是元素/节点附加到您的gifsContainer

    ParentNode.append() 方法在ParentNode 的最后一个孩子之后插入一组Node 对象或DOMString 对象。 DOMString 对象作为等效的 Text 节点插入。

    您应该使用new Image() 构造图像元素,然后将其附加:

    for (i in trendingResponse.data) {
        const image = new Image();
        image.src = trendingResponse.data[i].images.original.url;
    
        gifsContainer.append(image);
    }
    

    如果您更习惯使用document.createElement(),也可以:

    for (i in trendingResponse.data) {
        const image = document.createElement('img');
        image.src = trendingResponse.data[i].images.original.url;
    
        gifsContainer.append(image);
    }
    

    【讨论】:

    • 非常感谢您的帮助。这解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多