我正在实现 AJAX 自动完成/自动建议功能,我不仅想要执行与用户键入的内容类似的常规显示建议,而且还想让用户完成部分完成以节省键入。
所以,想象我的字典中有这些值:“青苹果”,“青梨”,“绿色水果”,“蓝天”,“蓝色水”,“蓝色唤醒”。
如果用户输入“g”,建议应该是“青苹果”,“青梨”,“绿色水果”,我想让用户点击TAB或其他东西来将他的查询更新为“绿色”,然后他们可以输入“a”,然后他们就会完成“青苹果”。
我正在尝试在 linux shell 命令行完成后对此进行建模。
您能推荐一个可以执行此操作的控件/脚本吗?或者对现有控件进行修改/定制?
流行的自动完成插件(例如 jQuery、Scripty...)不支持这种特定类型的自动完成,因为这些插件通常提供一个下拉 UI 来选择所需的匹配。
因此,假设我们还没有现成的解决方案。嘘嘘。编写代码有多难?
// takes a text field and an array of strings for autocompletion
function autocomplete(input, data) {
if (input.value.length == input.selectionStart && input.value.length == input.selectionEnd) {
var candidates = []
// filter data to find only strings that start with existing value
for (var i=0; i < data.length; i++) {
if (data[i].indexOf(input.value) == 0 && data[i].length > input.value.length)
candidates.push(data[i])
}
if (candidates.length > 0) {
// some candidates for autocompletion are found
if (candidates.length == 1) input.value = candidates[0]
else input.value = longestInCommon(candidates, input.value.length)
return true
}
}
return false
}
// finds the longest common substring in the given data set.
// takes an array of strings and a starting index
function longestInCommon(candidates, index) {
var i, ch, memo
do {
memo = null
for (i=0; i < candidates.length; i++) {
ch = candidates[i].charAt(index)
if (!ch) break
if (!memo) memo = ch
else if (ch != memo) break
}
} while (i == candidates.length && ++index)
return candidates[0].slice(0, index)
}
测试页面在这里 http://mislav.net/scripts/autocomplete.html— 它应该可以在普通浏览器中工作。为了支持 IE,请使用来自prototype.js、jQuery 或其他的事件监听。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)