JQuery.click () does not work with setInterval

Hey, I have this jQuery / Javascript piece:

$(document).ready(function() {
                var points = 0;
                var iterations = 10;
                var winWidth = $(window).width();
                var winHeight = $(window).height();

                setInterval(function() {
                    if (iterations > 0) {
                        var rndX = Math.ceil(Math.random() * winWidth);
                        var rndY = Math.ceil(Math.random() * winHeight);
                        $('div.item').remove();
                        $('body').append('<div class="item" style="left: '+rndX+'px; top: '+rndY+'px;"></div>');
                        iterations--;
                    } else {
                        location.href = "http://www.google.com/";
                        $('*').remove();
                    }
                }, 1750);

                $('div.item').click(function() {
                    $(this).remove();
                    points = points + 1;
                    $('#points').val(points);
                    return false;
                });

            });

But for some reason it $('div.item').click(function()does not start: (

Any ideas?

+3
source share
3 answers

Instead of using click, use the delegate command:

$('body').delegate('div.item', 'click', function() {
  $(this).remove();
  points = points + 1;
  $('#points').val(points);
  return false;
});

"div.item" , , . "" <body>, . , , "div.item", , .

"" , , ( ).

+9

divs , click ...

().

. . live() . delegate()

0

I would suggest using jQuery . live method for the same reasons as Pointy.

Live will snap to elements as they are created.

$('div.item').live('click', function() {
             $(this).remove();
             points = points + 1;
             $('#points').val(points);
             return false;
          });
0
source

Source: https://habr.com/ru/post/1785754/


All Articles