我有一个使用javascript的自定义自动完成功能,该功能在keyup函数下面调用,而keyup函数依次调用一个Web服务以获取结果。它会产生结果,但是当我在该字段中快速键入字符时,将逐渐为每个字符逐步细化结果,因此UI的最终感觉似乎很慢。是否有任何方法可以设置键入延迟当用户在字段中输入大量的暂停时,将调用ACCrequestSuggestions函数调用服务。还是有其他更好的方法使用jvascript处理此问题。请帮忙。
/**
* Handles keyup events.
*/
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
var iKeyCode = oEvent.keyCode;
//for backspace (8) and delete (46), shows suggestions without typeahead
if (iKeyCode == 8 || iKeyCode == 46) {
ACCrequestSuggestions(this, false);
//make sure not to interfere with non-character keys
} else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
//ignore
} else {
//request suggestions from the suggestion provider with typeahead
ACCrequestSuggestions(this,true);
}
};
/**
* Generate results and create the autocomplete drop down
*/
ACCrequestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
bTypeAhead /*:boolean*/) {
var aSuggestions = [];
// suggestions function will invoke service call to generate results based on input
aSuggestions = new Suggestions();
//provide suggestions to the control by building div of results
oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};
更新:
我按照建议使用settimeout,它很好用。输入时感觉更快。我的websetvice数据不是静态数据集。网络服务根据我输入的字符进行搜索。所以我不能在客户端缓存数据。所以我无能为力。
var timeout; // scope global
if (timeout != "")
{
clearTimeout(timeout);
}
timeout = setTimeout(function(){
//Code to retrieve suggestions
},50);
最佳答案
您可以使用setTimeout()
创建延迟,并在注册了多个击键之后仅调用一次ACCrequestSuggestions
:
AutoSuggestControl.prototype.handleKeyUp = (function() {
var timer;
return function (oEvent) {
var that = this;
try {
clearTimeout(timer); //stop timeout on key up if it's already running
} catch(ignore) {}
//call your code with a given delay
timer = setTimeout(function() {
/***your original code***/
var iKeyCode = oEvent.keyCode;
//for backspace (8) and delete (46), shows suggestions without typeahead
if (iKeyCode == 8 || iKeyCode == 46) {
ACCrequestSuggestions(that, false);
//make sure not to interfere with non-character keys
} else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
//ignore
} else {
//request suggestions from the suggestion provider with typeahead
ACCrequestSuggestions(that,true);
}
}, 300); //300 ms should be nice for performance and also for user experience
}
})();
请标记为在小于300ms的距离内敲击多个键时,此版本仅在按下最后一个键时调用
ACCrequestSuggestions
。这可能会引起问题,但是通常只会向用户显示一个结果,并且当然应该是最后一次按键产生的结果。