【问题标题】:keypresss event automatically fires after text input loses focus and gained focus againkeypresss 事件在文本输入失去焦点并再次获得焦点后自动触发
【发布时间】:2015-01-29 05:19:42
【问题描述】:

该脚本用于写下来以控制台用户的输入。如果这是文本输入第一次获得焦点,则一切顺利。但是一旦输入失去焦点并再次获得焦点,它会使我在输入中键入的字符加倍。我跟踪并看到虽然我只点击了 1 次,但函数 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);         
        }
    }


}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您多次绑定同一个处理程序,但从未解除绑定。每次您专注于该领域时,您都会添加一个额外的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);         
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多