尽管输入被禁用,jQuery函数多次运行?

时间:2017-07-14 22:58:59

标签: javascript jquery

我遇到一个问题,即在第一次按键后函数(以及后续回调函数)继续运行,尽管事实上我是专门禁用输入和取消绑定按键。奇怪的是,这些额外的结果只有在经过了大量时间后才开始出现(我猜是10秒以上)。您可以在输入地址时转到http://isitsketch.com并在输入按钮上进行混搭,以查看此错误。相关代码是:

  $('.location-form').keypress(function(event){
    if (event.which == 13){
    $(this).find('input').attr('disabled','disabled');
        $(window).unbind("keypress")
        console.log('search entered')
        event.preventDefault();
        userAddress = $("#input1").val()
        address = userAddress.replace(/\s+/g, '+');
        getMaps(address)
        event.stopPropagation()
        return false;
    } else {
        return true;
      }
  });

显示结果的功能如下:

function displayResults(sketchLevel, robberies, assaults, burglaries, thefts, weapons, topFiveArr) {
  $('#newResults').append('<h4 id="feedback" style="color:white;text-align:center;">' + userAddress + '</h4>')
  $("<h2 id='result-level'>Sketch Level: <span class='redText'>"+ sketchLevel +"</span></h2>").appendTo("#newResults")
  $('<div id="indicator"><div id="bar"></div><div id="dial"></div></div>').appendTo("#newResults")
  $('<a id="tryAgain" class="waves-effect waves-light btn" href="http://isitsketch.com">Enter a New Address</a>').appendTo("#newResults")
  $('<p id="explanation">These results are based on NYC\'s OpenData information platform. The crimes have been weighted to reflect their severity. The resulting SketchLevel ranges from 0 (no crimes) to 2000+ (lots of severe crime activity).</p>').appendTo("#newResults")
  $('#newResults').append('<h4 id="topFive">Can you beat these scores?:</h4><ul id="topList"></ul>')
  for (i = 0; i < 5; i++){
    var currentTopArea = topFiveArr[i]['area']
    var currentTopRank = topFiveArr[i]['rank']
    $('#topList').append('<li style="color:white; font-size:1em;">' + currentTopArea + ': ' +'<span id="rankText">' + currentTopRank + '</span>' +'</li>')
  }
  var audio = new Audio('sound/gunsound.mp3')
  audio.play();

  if(sketchLevel <= 400) {
    $('#dial').addClass('sketchlevel1')
  }
    if(sketchLevel > 400 && sketchLevel <= 800) {
    $('#dial').addClass('sketchlevel2')
  }
    if(sketchLevel > 800 && sketchLevel <= 1400){
    $('#dial').addClass('sketchlevel3')
  }
    if(sketchLevel > 1500 && sketchLevel <= 2000) {
    $('#dial').addClass('sketchlevel4')
  }
  if(sketchLevel > 2000) {
    $('#dial').addClass('sketchlevel5')
  }
}

2 个答案:

答案 0 :(得分:1)

由于keypress事件处理程序绑定到.location-form,您需要从该元素取消绑定,而不是window。所以它应该是:

$('.location-form').unbind("keypress");

此外,.off()优于.unbind(),除非您需要与1.7之前的jQuery版本兼容。

答案 1 :(得分:0)

我想出了如何阻止它,虽然我仍然不知道为什么它首先发生。修复是这样的:

if(is_array($_POST['items'])){
    foreach($_POST['items'] as $index => $item){

        $key = key($item);

        if($key == 'image'){
            echo 'hello';
        }
    }
}

那就是说,如果其他人能够弄清楚它是如何/为什么绕过输入禁用线然后继续每10秒左右发布一次,那将是非常棒的。太奇怪了。