Javascript 在jquery中创建雪花

Javascript 在jquery中创建雪花,javascript,jquery,Javascript,Jquery,我使用jquery创建雪花。一切似乎都好,但我想做警报选项,当你点击特定的薄片,然后它应该提醒消息。但我实现了“点击”功能,警报选项会不断触发。我不知道我哪里出错了。我试过了,但是什么也没发生。 现在,我想提醒特定的点击。如何防止多个警报点击雪花。 谢谢。在每个雪花元素上每200毫秒绑定一个单击处理程序 看起来,generateSnow()将是绑定单击处理程序的好地方 您还可以在DOM ready上使用事件委派和绑定: $(document).on('click', '.snow', func

我使用jquery创建雪花。一切似乎都好,但我想做警报选项,当你点击特定的薄片,然后它应该提醒消息。但我实现了“点击”功能,警报选项会不断触发。我不知道我哪里出错了。我试过了,但是什么也没发生。

现在,我想提醒特定的点击。如何防止多个警报点击雪花。
谢谢。

在每个雪花元素上每200毫秒绑定一个单击处理程序

看起来,
generateSnow()
将是绑定单击处理程序的好地方

您还可以在DOM ready上使用事件委派和绑定:

$(document).on('click', '.snow', function() {
    alert('You clicked');
});

如果您只希望在单击雪花时发出警报,请将处理程序移动到雪花创建的位置,而不是当前雪花更新的位置

$('<div />')
    .addClass('snow')
    .css('top', snowTop)
    .css('left', snowLeft)
    .css('position','absolute')
    .html('*')
    .click(function() {
        alert('You Clicked');
    })
);
$(“”)
.addClass(“雪”)
.css('top',snowTop)
.css(‘左’,左)
.css('位置','绝对')
.html(“*”)
。单击(函数(){
警报(“您单击了”);
})
);

生成雪花后,只需将
单击
处理程序移动到
雪花
功能之外:


五片尖尖的雪花在我看来是不对的。我们有自己的选择,这是行不通的。添加新的
.snow
对象时,将不会创建处理程序。感谢您的回复并指出正确的方法。:)它起作用了great@DanielGimenez在
generateSnow
中绑定处理程序将在创建它们时绑定它们,而
on()
的事件委派版本在绑定时不要求元素存在。只有
文档
必须存在。
$('<div />')
    .addClass('snow')
    .css('top', snowTop)
    .css('left', snowLeft)
    .css('position','absolute')
    .html('*')
    .click(function() {
        alert('You Clicked');
    })
);
// this function is to alter the top of each snow, using the handy .each() jQuery method
function snowFalling(){

    // move the snow
    $('.snow').each(function(key, value){

        // check if the snow has reached the bottom of the screen
        if( parseInt($(this).css('top')) > windowHeight - 80 ) {

            // remove the snow from the HTML DOM structure
            $(this).remove();
        }       

        // set up a random speed
        var fallingSpeed = Math.floor(Math.random() * 5 + 1);

        // set up a random direction for the snow to move
        var movingDirection = Math.floor(Math.random()*2);

        // get the snow's current top
        var currentTop = parseInt($(this).css('top'));      

        // get the snow's current top
        var currentLeft = parseInt($(this).css('left'));                

        // set the snow's new top
        $(this).css('top', currentTop + fallingSpeed ); 

        // check if the snow should move to left or move to right
        if( movingDirection === 0){

            // set the snow move to right
            $(this).css('left', currentLeft + fallingSpeed );   

        }else {

            // set the snow move to left
            $(this).css('left', currentLeft + -(fallingSpeed) );                

        }                   

    }); 

    // repeat the rollIt() function for each 200 microseconds
    window.setTimeout(snowFalling, 200);            

}        

// call the function when the document is loaded completely
generateSnow();  
snowFalling();

$('.snow').click(function() {
    alert('You Clicked');
});