1

I am new to Jquery and I can't seem to find a what is the cause of this issue.

I have a variable which gets a new value each time the function GameStart() runs, to this function I am trying to create a pause function, in the pause function I have an alert which displays the value of the variable (just as a test for now).

The issue is that the pause click event does not only alert the current value but also all the previous ones.

What is the cause of this? And what can I do to fix it?

In fiddle example press Start and the press Pause every now and then to see all values.

JSFIDDLE: http://jsfiddle.net/Limitedmoves/SrWJP/

$(document).ready(function () {
    $('.butResize').click(function () {
        alert("hello"); 
            GameStart();    
    });

    function GameStart(){
        //Set needed random variables below
        var vSetTimer = 1000 * Math.floor(Math.random() * 10);
        var vBarWood = 1 + Math.floor(Math.random() * 400); 

        setTimeout(function () {
        //alert(vSetTimer);
            $('.div').animate({height: vBarWood }, 500);
        GameStart();    
    }, vSetTimer); //Time lenght set from vSetTime variable

    $('.pause').click(function () { //Start pause function
        var vTempTimer= vSetTimer;
        console.log(vTempTimer);    
    });
}
});

I have looked around here at stackoverflow and found similar behavior being solved by using "return", but from what I have tried it hasn't helped.

Thanks beforehand! :)

4

3 回答 3

3

每次被调用时,都会向元素GameStart添加一个新的事件处理程序。$('.pause')

因此,您第二次调用时GameStart,单击.pause将触发 2 个功能。

一个简单的解决方案是unbind在添加新的单击处理程序之前对所有先前添加的单击处理程序:

$('.pause').unbind('click').click(function() {
    ...
});

编辑: 要获得更好和更清洁的解决方案,请参阅@Björn Roberg 的回答

于 2013-08-20T09:33:08.720 回答
1

@ju-k 的解释是正确的,并提供了一个可行的解决方案。但是,另一种解决方案可能如下所示:

$(document).ready(function () {

    $('.butResize').click(function () {
        alert("hello");
        GameStart();
    });

    var vSetTimer;
    var vBarWood;

    function GameStart(){
    //Set needed random variables below
        vSetTimer = 1000 * Math.floor(Math.random() * 10);
        vBarWood = 1 + Math.floor(Math.random() * 400);

        setTimeout(function () {

            //alert(vSetTimer);

            $('.div').animate({height: vBarWood }, 500);

            GameStart();    

        }, vSetTimer); //Time lenght set from vSetTime variable
    }

    $('.pause').click(function () { //Start pause function
        console.log(vSetTimer);
    });

});

即将变量移动到外部范围,这也可以解决它,而不必每次都取消绑定/绑定。

编辑 正如评论中所指出的,没有解释为什么它在这个答案中表现得如此。开始:

如其他答案所述,问题中行为的原因是,每次调用 GameStart 时,都会将点击处理程序附加到与选择器“.pause”匹配的元素中。即第一次运行 GameStart 时,带有闭包变量 (vSetTimer) 的处理程序被附加到“.pause”按钮。下一次 GameStart 运行时,它会做同样的事情,等等。这个闭包不会改变,这就是为什么第一次出现的相同数字第二次出现,然后是下一个闭包 var,等等。

于 2013-08-20T09:42:33.723 回答
0

看看更新的小提琴,我添加了一个 cleartimeout 并解决了你的问题。

clearTimeout(timer);

我也把randNumber外部reSize()范围。

于 2013-08-20T09:37:55.317 回答