为什么刷新后内容不显示

Why is the content not showing after refresh

我正在创建一个允许用户使用 GIPHY API 搜索 GIF 的网络应用程序。 我添加了应该刷新页面的代码,然后加载所有 GIF。

// the Div where the GIFs from GIPHY will be appended to.
const imagesDiv = document.getElementById("imagesDiv");
// The user input -- the name of GIFs searched. Ex. Cats, Dogs, etc.
const search = document.getElementById("search");
// The search button for GIFs.
const submit = document.getElementById("submit");
// When pressed, it begins searching. 
submit.addEventListener("click", function () {
  // Refresh page first to get rid of old search results
  window.location.reload();
  getData(search.value);

});

// Code that uses GIPHY Api
function getData(query) {

  // fetch data from GIPHY, using the user's input(ex. dogs) to replace word in the link
  fetch(
    "https://api.giphy.com/v1/gifs/search?q=" +
    query +
    "&api_key=8UHgk4rc0ictTp8kMXNGHbeJAWwg19yn&limit=5"
  )
    .then(function (response) {
      return response.json();
    })
    .then(function (myJson) {
      renderData(myJson);

    });

  function renderData(data) {
    console.log(data.data);
    // For loop runs as many times as needed to get all GIFs
    for (let i = 0; i < data.data.length; i++) {
      // create img element to represent the GIFs
      const img = document.createElement("img");
      // give className for css styling
      img.className = "gifs";
      // give img url to get the GIFs
      img.src = data.data[i].images.original.url;
      // put them into a div
      imagesDiv.appendChild(img);
    }
  }

}

相反,它加载然后刷新页面,删除所有 GIF,然后它们才能在屏幕上弹出

当您重新加载页面时,包括脚本在内的所有内容都将被重新加载。 所以你要求页面重新加载,然后尝试加载 GIF,此代码将尝试加载 GIF,但重新加载已经开始。

您看到的东西 "it load then refreshes the page" - 从缓存 GIF 加载,几乎立即添加到页面。

当您只是从 DOM 中删除带有 GIF 的元素并添加一个新元素时,您可能希望以某种方式更新您的代码。

而不是

window.location.reload();

你可以写:

while (imagesDiv.firstChild) {
  imagesDiv.removeChild(imagesDiv.firstChild);
}

您的代码结束于 "window.location.reload();"。

现在好像没机会执行了"getData(search.value);".

试试这个,

submit.addEventListener("click", function () {
  imagesDiv.innerHTML = "";
  getData(search.value);

});