自己學習javascript之餘,實現了輸入框的智能提示功能,其代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="content">
<p>Type in a color in lowercase:<br /></p>
<input type ="text" value ="" id ="textColor" onkeyup ="TextUtil.autoSuggest(this,arrColors,'lstColors');" /><br />
<p>nidddddddddddddddddddddddddddddd</p>
<select id="lstColors" size ="5" style ="width:200px; visibility:hidden; position :absolute ;" onclick ="setText(this,'textColor');">
</select>
</div>
<script type ="text/javascript" >
var arrColors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet", "brown", "black", "tan", "ivory", "navy", "aqua", "purple", "pink", "gray", "silver"];
arrColors.sort();
function setText(oListBox, otextColorId) {
var textColor = document.getElementById(otextColorId);
if (oListBox.selectedIndex > -1) {
textColor.value = oListBox.options[oListBox.selectedIndex].text;
}
oListBox.style.visibility = "hidden";
}
var TextUtil = new Object;
TextUtil.autoSuggestMatch = function(sText, arrayValues) {
var arrayResult = new Array;
if (sText != "") {
for (var i = 0; i < arrayValues.length; i++) {
if (arrayValues[i].indexOf(sText) == 0) {
arrayResult.push(arrayValues[i]);
}
}
}
return arrayResult;
}
TextUtil.autoSuggest = function(oTextBox, arrValues, sListboxId) {
var listbox = document.getElementById(sListboxId);
listbox.style.visibility = "visible";
listbox.style.top = "70px";
for (var i = listbox.options.length - 1; i >= 0; i--) {
listbox.remove(i);
}
var arrayMatch = TextUtil.autoSuggestMatch(oTextBox.value, arrValues);
for (var i = 0; i < arrayMatch.length; i++) {
var oOption = document.createElement("option");
oOption.appendChild(document.createTextNode(arrayMatch[i]));
if (arguments.length == 3) {
oOption.setAttribute("value", i);
}
listbox.appendChild(oOption);
}
}
function setIn(listColorId) {
var listBox = document.getElementById(listColorId);
listBox.style.visibility = "hidden";
}
</script>
</body>
</html>
不過裏面有幾個問題,一是該實現主要是通過客戶端javascript實現,當庫比較大時,其效率和可行性將是瓶頸,自己提出設想如下:
1、通過異步通訊實現服務器端的文本存儲和更新
2、檢索方式可使通過B+樹來實現,以便替代目前爲止效率地下的檢索
由於時間原因,目前先實現到這裏。