按键事件在文本输入失去焦点后自动触发并再次获得焦点

时间:2015-01-28 21:08:49

标签: javascript

该脚本用于向下记录控制用户的输入。如果这是第一次文本输入获得焦点,那么一切顺利。但是一旦输入失去焦点并再次获得焦点,它就会使输入中输入的字符加倍。我跟踪并看到虽然我只点击了一次,但是函数autocomplete()被调用了两次。那么,这里会发生什么?

更新:输入失败并再次获得焦点的次数越多,自动调用该方法的次数就越多!

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


}

1 个答案:

答案 0 :(得分:2)

您多次绑定同一个处理程序,而不会将其解绑。每当您专注于该字段时,您都会添加额外的autoComplete(event)来电。当.off()事件触发该字段时,您需要在按键上调用blur

$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);         
        }
    }
}
相关问题