【发布时间】: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