簡體   English   中英

每次運行,JavaScript函數都會循環兩次

[英]JavaScript function loops twice as many times every time ran

我正在嘗試在JavaScript(+ JQuery)中使用類似於聲音校准器系統的功能。 它從一個頻段開始播放,詢問用戶是否可以聽到它-然后它是否可以知道其系統的最低頻率,如果不能知道,則上升到下一個頻段,然后重新檢查,直到找到最低的頻率。

但是,當我運行該函數時,它似乎每次都運行兩次。 從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);
}

...其余的...

每次都要綁定一個附加的單擊處理程序,如果要更改它,只需.unbind() ,如下所示:

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

...與#no相同,否則,每次調用.click()您都將附加一個新的click事件處理程序,但不會刪除前一個事件處理程序,因此都將被執行...並每次都添加一個附加的處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM