Почему моя функция JSON не распознает мою кнопку .createElement? - PullRequest
0 голосов
/ 26 сентября 2019

Поле ввода поиска создает кнопку из пользовательского текста, используя .createElement.Эта кнопка добавляется аналогично другим кнопкам HTML.Нажатие на кнопку запускает функцию, которая получает параметры поиска JSON из .innerHTML кнопки, на которую нажали.Почему моя функция 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");
    }
  });
});

1 Ответ

0 голосов
/ 27 сентября 2019

По умолчанию .on( events, handler ) не работает для динамически создаваемых элементов.

Исходя из этого вопроса и ответа , вы можете использовать $(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>
...