为什么我的JSON函数无法识别我的.createElement按钮?

问题描述 投票:0回答:1

搜索输入字段使用.createElement从用户文本中创建一个按钮。该按钮与其他HTML按钮相同。单击按钮会触发一个函数,该函数从单击的按钮的.innerHTML获取JSON搜索参数。为什么我的JSON函数无法识别此新按钮?

HTML
<!DOCTYPE html>
    <html lang="en-us">
      <head>
        <title>Giphy API</title>
        <meta charset="utf-8" />
        <meta name="description" content="Giphy API" />
        <meta name="keywords" content="javascript, api, web developement" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous"
        />
      </head>
      <body>
        <div class="container">
          <form id="button-form row">
            <label for="button-input"></label>
            <input type="text" id="button-input" />
            <input id="add-button" type="submit" value="Search Giphy" />
          </form>
        </div>
        <div class="container">
          <div class="col">
            <button class="gif-button">dogs</button>
            <button class="gif-button">cats</button>
            <button class="gif-button">birds</button>
          </div>
        </div>

        <div class="container gifs">
          <div class="images row"></div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript" src="assets/javascript/script.js"></script>
      </body>
    </html>
Javascript
let gifButton = document.querySelector(".gif-button").innerHTML;
let search = document.getElementById("button-input");

//       ******* SEARCH GIFS *******
$("#add-button").on("click", function() {
  event.preventDefault();
  //on click create button from input text
  var newButton = document.createElement("button");
  newButton.innerHTML = search.value;
  newButton.setAttribute("class", "gif-button");
  $(".col").prepend(newButton);
});

//       ******* CREATE GIFS *******
// Event listener for our gif-button
$(".gif-button").on("click", function() {
  // Storing our giphy API URL for random images
  let selection = this.innerHTML;
  let queryURL =
    "https://api.giphy.com/v1/gifs/random?api_key=BkaUZZWcFij6J7AoQj3WtPb1R2p9O6V9&tag=" +
    selection;

  // Perfoming an AJAX GET request to our queryURL
  $.ajax({
    url: queryURL,
    method: "GET"
  })

    // After the data from the AJAX request comes back
    .then(function(response) {
      // Saving the image_original_url property
      var imageUrl = response.data.images.fixed_height.url;

      // Creating and storing an image tag
      var image = $("<img>" + "</br>" + "</br>");

      // Setting the Image src attribute to imageUrl
      image.attr("src", imageUrl);
      image.attr("alt", gifButton);
      image.attr("class", "gif");
      image.attr("data-state", "still");
      image.attr("data-still", response.data.images.fixed_height_still.url);
      image.attr("data-animate", response.data.images.fixed_height.url);

      // Prepending the image to the images div
      $(".images").prepend(image);
    });

  //animate on click
  $(".images").on("click", function() {
    console.log("click");
    // The attr jQuery method allows us to get or set the
    // value of any attribute on our HTML element
    var state = $(".gif").attr("data-state");

    if (state === "still") {
      // If the clicked image's state is still,
      // update its src attribute to what its data-animate value is.
      // Then, set the image's data-state to animate
      $(".gif").attr("src", $(".gif").attr("data-animate"));
      $(".gif").attr("data-state", "animate");
      console.log("animate");
    } else {
      // Else set src to the data-still value
      $(".gif").attr("src", $(".gif").attr("data-still"));
      $(".gif").attr("data-state", "still");
      console.log("still");
    }
  });
});
json function createelement
1个回答
0
投票

默认情况下,.on( events, handler )不适用于动态创建的元素。

基于this question and answer,您可以使用$(PARENT SELECTOR).on( events, SELECTOR, handler)解决问题。在您的代码中,它可以是$(".col").on("click", ".gif-button", function() { ... });

这里是完整的代码:

let gifButton = document.querySelector(".gif-button").innerHTML;
let search = document.getElementById("button-input");

//       ******* SEARCH GIFS *******
$("#add-button").on("click", function() {
  event.preventDefault();
  //on click create button from input text
  var newButton = document.createElement("button");
  newButton.innerHTML = search.value;
  newButton.setAttribute("class", "gif-button");
  $(".col").prepend(newButton);
});

//       ******* CREATE GIFS *******
// Event listener for our gif-button
$(".col").on("click", ".gif-button", function() {
  // Storing our giphy API URL for random images
  let selection = this.innerHTML;
  let queryURL =
    "https://api.giphy.com/v1/gifs/random?api_key=BkaUZZWcFij6J7AoQj3WtPb1R2p9O6V9&tag=" +
    selection;

  // Perfoming an AJAX GET request to our queryURL
  $.ajax({
    url: queryURL,
    method: "GET"
  })

    // After the data from the AJAX request comes back
    .then(function(response) {
      // Saving the image_original_url property
      var imageUrl = response.data.images.fixed_height.url;

      // Creating and storing an image tag
      var image = $("<img>" + "</br>" + "</br>");

      // Setting the Image src attribute to imageUrl
      image.attr("src", imageUrl);
      image.attr("alt", gifButton);
      image.attr("class", "gif");
      image.attr("data-state", "still");
      image.attr("data-still", response.data.images.fixed_height_still.url);
      image.attr("data-animate", response.data.images.fixed_height.url);

      // Prepending the image to the images div
      $(".images").prepend(image);
    });

  //animate on click
  $(".images").on("click", function() {
    console.log("click");
    // The attr jQuery method allows us to get or set the
    // value of any attribute on our HTML element
    var state = $(".gif").attr("data-state");

    if (state === "still") {
      // If the clicked image's state is still,
      // update its src attribute to what its data-animate value is.
      // Then, set the image's data-state to animate
      $(".gif").attr("src", $(".gif").attr("data-animate"));
      $(".gif").attr("data-state", "animate");
      console.log("animate");
    } else {
      // Else set src to the data-still value
      $(".gif").attr("src", $(".gif").attr("data-still"));
      $(".gif").attr("data-state", "still");
      console.log("still");
    }
  });
});
<!DOCTYPE html>
    <html lang="en-us">
      <head>
        <title>Giphy API</title>
        <meta charset="utf-8" />
        <meta name="description" content="Giphy API" />
        <meta name="keywords" content="javascript, api, web developement" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous"
        />
      </head>
      <body>
        <div class="container">
          <form id="button-form row">
            <label for="button-input"></label>
            <input type="text" id="button-input" />
            <input id="add-button" type="submit" value="Search Giphy" />
          </form>
        </div>
        <div class="container">
          <div class="col">
            <button class="gif-button">dogs</button>
            <button class="gif-button">cats</button>
            <button class="gif-button">birds</button>
          </div>
        </div>

        <div class="container gifs">
          <div class="images row"></div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      </body>
  <html>
© www.soinside.com 2019 - 2024. All rights reserved.