2015-01-28 1 views
0

스크립트는 사용자 입력을 콘솔에 기록하는 데 사용됩니다. 텍스트 입력이 포커스를 얻는 것이 처음이라면 모든 것이 잘됩니다. 그러나 입력이 초점을 잃고 초점을 다시 얻으면 입력에 입력 한 문자가 두 배가됩니다. 추적하고 본 것은 1 번만 탭했지만 autocomplete() 함수는 두 번 호출되었습니다. 여기, 어떻게 될까요?텍스트 입력이 포커스를 잃고 다시 포커스를 얻은 후에 keypresss 이벤트가 자동으로 실행됩니다.

업데이트 : 입력이 손실되어 다시 초점을 맞출수록 메서드가 자동으로 더 많이 호출됩니다.

var userInput = ''; //store input of users 
var $userInput = $('#userInput'); // text input element 

$userInput.on('focus', function(){ 
    console.log('gain focus'); 
    var matchedArray = []; 
    init($userInput, matchedArray); 

}); 

function init($el, matchedArray){ 
    $el.on('keypress', function(event){ 
     autoComplete(event);   
    }); 

    function autoComplete(evt){ 
     if(evt.which !== 8){ 
      userInput += String.fromCharCode(evt.which); 
      console.log(userInput); 
     }else{ 
      userInput = userInput.slice(0, userInput.length - 1); 
      console.log('after backspace: '+userInput);   
     } 
    } 


} 

답변

2

동일한 핸들러를 언 바운드하지 않고 여러 번 바인딩하고 있습니다. 필드에 집중할 때마다 autoComplete(event) 통화가 추가됩니다. 해당 필드에 blur 이벤트가 발생하면 키 누르기에서 .off()으로 전화해야합니다.

$userInput.on('focus', function(){ 
    console.log('gain focus'); 
    var matchedArray = []; 
    init($userInput, matchedArray); 
}); 

function init($el, matchedArray){ 
    var handler = function(event) { 
     autoComplete(event); 
    }   
    $el.on('keypress', handler); 

    $el.on('blur', function() { 
     $el.off('keypress', handler); 
    }); 

    function autoComplete(evt){ 
     if(evt.which !== 8){ 
      userInput += String.fromCharCode(evt.which); 
      console.log(userInput); 
     }else{ 
      userInput = userInput.slice(0, userInput.length - 1); 
      console.log('after backspace: '+userInput);   
     } 
    } 
} 
관련 문제