jQuery .click()不使用setInterval [英] jQuery .click() not working with setInterval

查看:204
本文介绍了jQuery .click()不使用setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有这条jQuery / Javascript:

Hey, I have this piece of jQuery/Javascript:

$(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;
                });

            });

但出于某种原因, $('div.item')。点击(function()不启动:(

But for some reason, the $('div.item').click(function() doesn't fire up :(

任何想法?

推荐答案

不使用click,而是使用delegate:

Instead of using "click", use "delegate":

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

当你的间隔处理程序代码从文档中删除所有div.item元素时,这也将删除你建立的处理程序。通过使用委托,你只需要在< body> 元素,它利用事件冒泡来处理所有点击。来自与div.item选择器匹配的元素的那些将使用您的代码处理,就像如果处理程序已直接绑定到元素。

When your interval handler code removes all the "div.item" elements from the document, that will also remove the handlers you established. By using "delegate" instead, you put just one handler on the <body> element, and it takes advantage of event bubbling to handle all the clicks. Those that come from elements that match the "div.item" selector will be handled with your code, just as if the handler had been directly bound to the elements.

因为委托机制在事件实际发生时应用选择器,自首次接收页面后是否存在目标元素或者是否仅动态添加元素(如代码中的情况)无关紧要。

Because the "delegate" mechanism applies the selector at the time the events actually happen, it doesn't matter whether the target element existed since the page was first received or if the element was just dynamically added (as is the case in your code).

这篇关于jQuery .click()不使用setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆