jQuery .click()不使用setInterval

嘿,我有这条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('
'); 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').click(function()不会启动:(

有任何想法吗?

而不是使用“点击”,使用“委托”:

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

当您的间隔处理程序代码从文档中删除所有“div.item”元素时,这也将删除您建立的处理程序。 通过使用“委托”,您只需在元素上放置一个处理程序,它利用事件冒泡来处理所有单击。 来自与“div.item”选择器匹配的元素的那些将使用您的代码处理,就像处理程序已直接绑定到元素一样。

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

当您尝试将单击函数绑定到元素时,您的div不存在…

您需要提前绑定它们(动态)。

看.live()和.delegate()

我建议使用JQuery的.live方法,原因与Pointy类似。

Live将在创建元素时绑定到元素。

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