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);
}
}
}