【问题标题】:JavaScript function loops twice as many times every time ranJavaScript 函数每次运行都会循环两倍
【发布时间】:2023-04-08 06:09:01
【问题描述】:

我正在尝试在 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);
}

...其余的...

【问题讨论】:

    标签: javascript jquery function loops


    【解决方案1】:

    你每次都绑定一个额外的点击处理程序,如果你想改变它,只需先.unbind(),像这样:

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

    ...#no 也是如此,否则每次调用 .click() 时,您都会附加一个新的 click 事件处理程序,但不会删除前一个事件处理程序,因此两者都会被执行...和每次增加一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 2018-10-28
      • 2020-07-22
      相关资源
      最近更新 更多