Добавление onclick-listener после добавления нового div - PullRequest
0 голосов
/ 12 апреля 2020

Итак, я добавляю круги на арену, которая рандомизирована.

Проблема, с которой я столкнулся, заключается в том, что после добавления круга на нем не работает щелчок мыши.

Вот что я пробовал:

manyBalls = setInterval(function() {
    $("<div class='circle-gm-2'></div>").appendTo(".arena-2").css({
      backgroundColor: circleColor,
      width:(circleRange).val(),
      height:(circleRange).val(),
      //Here comes the random magic position of the circle
      marginLeft: Math.floor(Math.random() * arenaWidth),
      marginTop: Math.floor(Math.random() * arenaHeight)
    });
  }, 300,function(){
    $(this).on("click", function(e){
      //When the user clicks on the circle inside the arena shit will happen
      //Stopping the Propagation because we are counting misses if the user presses the arena and the circle is a child of it...
      e.stopPropagation();
      hits++;
      //Counting how many hits
      $(".totalhits").text(hits);
      //Removing the circle
      $(this).remove();
    });
  });

Также это не работает:

 $(".circle-gm-2").on("click", function(e){
  //When the user clicks on the circle inside the arena shit will happen
  //Stopping the Propagation because we are counting misses if the user presses the arena and the circle is a child of it...
  e.stopPropagation();
  hits++;
  //Counting how many hits
  $(".totalhits").text(hits);
  //Removing the circle
  $(this).remove();
});

Поскольку он будет добавлять обработчик событий во все «.circle-gm-2», показываемые каждый раз.

Как сделать так, чтобы ТОЛЬКО текущий добавленный круг на арену, добавлен список событий.

Ответы [ 2 ]

0 голосов
/ 12 апреля 2020

Я понял это.

Забыл, что с помощью jQuery вы можете связать воедино действия / методы. Поэтому самый простой способ сделать это будет:

//Appending the circle to the arena
  manyBalls = setInterval(function() {
    $("<div class='circle-gm-2'></div>").on("click",function(e){
      //When the user clicks on the circle inside the arena shit will happen
      //Stopping the Propagation because we are counting misses if the user presses the arena and the circle is a child of it...
      e.stopPropagation();
      hits++;
      //Counting how many hits
      $(".totalhits").text(hits);
      //Removing the circle
      $(this).remove();
    }).appendTo(".arena-2").css({
      backgroundColor: circleColor,
      width:(circleRange).val(),
      height:(circleRange).val(),
      //Here comes the random magic position of the circle
      marginLeft: Math.floor(Math.random() * arenaWidth),
      marginTop: Math.floor(Math.random() * arenaHeight)
    }).animate({opacity:0}, 1500, function() {
      $(this).remove();
      miss++;
    });
  }, 500);

Перед добавлением только что созданного div вы добавляете слушателя, а затем добавляете его.

0 голосов
/ 12 апреля 2020

Попробуйте:

$(document).on("click", ".circle-gm-2", function(e){
  //When the user clicks on the circle inside the arena shit will happen
  //Stopping the Propagation because we are counting misses if the user presses the arena and the circle is a child of it...
  e.stopPropagation();
  hits++;
  //Counting how many hits
  $(".totalhits").text(hits);
  //Removing the circle
  $(this).remove();
});

Надеюсь, это поможет.

...