jquery.AutoComplete.js中文修正版(支持firefox)
2024-05-06 14:10:37
供稿:网友
代码如下:
jQuery.autocomplete = function(input, options) {
// Create a link to self
var me = this;
// Create jQuery object for input element
var $input = $(input).attr("autocomplete", "off");
// Apply inputClass if necessary
if (options.inputClass) $input.addClass(options.inputClass);
// Create results
var results = document.createElement("div");
// Create jQuery object for results
var $results = $(results);
$results.hide().addClass(options.resultsClass).css("position", "absolute");
if (options.width > 0) $results.css("width", options.width);
// Add to body element
$("body").append(results);
input.autocompleter = me;
var timeout = null;
var prev = "";
var active = -1;
var cache = {};
var keyb = false;
var hasFocus = false;
var lastKeyPressCode = null;
// flush cache
function flushCache() {
cache = {};
cache.data = {};
cache.length = 0;
};
// flush cache
flushCache();
// if there is a data array supplied
if (options.data != null) {
var sFirstChar = "", stMatchSets = {}, row = [];
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if (typeof options.url != "string") options.cacheLength = 1;
// loop through the array and create a lookup structure
for (var i = 0; i < options.data.length; i++) {
// if row is a string, make an array otherwise just reference the array
row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
// if the length is zero, don't add to list
if (row[0].length > 0) {
// get the first character
sFirstChar = row[0].substring(0, 1).toLowerCase();
// if no lookup array for this character exists, look it up now
if (!stMatchSets[sFirstChar]) stMatchSets[sFirstChar] = [];
// if the match is a string
stMatchSets[sFirstChar].push(row);
}
}
// add the data items to the cache
for (var k in stMatchSets) {
// increase the cache size
options.cacheLength++;
// add to the cache
addToCache(k, stMatchSets[k]);
}
}
$input
.keydown(function(e) {
// track last key pressed
lastKeyPressCode = e.keyCode;
switch (e.keyCode) {
case 38: // up
e.preventDefault();
moveSelect(-1);
break;
case 40: // down
e.preventDefault();
moveSelect(1);
break;
case 9: // tab
case 13: // return
if (selectCurrent()) {
// make sure to blur off the current field
$input.get(0).blur();
e.preventDefault();
}
break;
default:
active = -1;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function() { onChange(); }, options.delay);
break;
}
})
.focus(function() {
// track whether the field has focus, we shouldn't process any results if the field no longer has focus
hasFocus = true;
})
.blur(function() {
// track whether the field has focus
hasFocus = false;
hideResults();
})
.bind("input", function() {