2010-12-13 141 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每次增加一個。