繁体   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