2010-12-13 138 views
0

我试图在JavaScript(+ JQuery)中使用一个像声音校准器系统的函数。它从一个频段开始,播放它,询问用户是否可以听到它 - 然后如果它知道它的系统的最低频率,并且如果它不知道它会到达下一个频段,然后重新检查等,直到找到最低频率。JavaScript函数循环每次循环两次

但是,当我运行该函数时,它似乎每次运行两次自己多次。从testFreqNum警报中,我可以看到它第一次添加1次,第二次添加1然后再次添加它,第三次它做了4次,然后是8等。

可能是一个容易的错误修复 - 我'JavaScript新手,所以也许你可以马上看到它?谢谢。

function testFreq(band, testType){ 

if (testType == 'testLow') { 
    $('#calibrationText').html('<h5>Testing ' + freqs[band] + 'Hz...</h>'); 
    playSound('Tones', band); 
    //window.setTimeout(function(){ 
    $('#calibrationText').html('<h5>Could you hear ' + freqs[band] + 'Hz clearly?</h>'); 
    $('#yes').fadeIn(500).click(function(){ 

     bandMin = band;//sets randGen's min availible band value 
     testFreqNum = 31;//sets test frequency to upper high 
     testFreq(testFreqNum, 'testHigh');//runs calibrator again in high mode starting band 31 
     $('#yes').fadeOut(500); 
     $('#no').fadeOut(500); 
    }); 

    $('#no').fadeIn(500).click(function(){ 

     testFreqNum = testFreqNum + 1; 
     alert(testFreqNum); 
     testFreq(testFreqNum, 'testLow');//runs calibrator again in low mode 
     //$('#yes').fadeOut(500); 
     //$('#no').fadeOut(500); 
    }); 
    // }, 4000); 
} 

...其余...

回答

4

每次要绑定的额外单击处理程序,如果你想改变它,只是.unbind()第一,像这样:

$('#yes').fadeIn(500).unbind("click").click(function(){ 

...和#no相同,否则每次拨打电话.click()时,您都附加了一个新的click事件处理程序,但没有删除前一个,因此两者都得到执行...... d每次增加一个。