Ajax的自动完成(或自动提示)用TAB完成/自动填充类似于shell命令行完成?类似于、命令行、自动完成、提示

2023-09-11 00:46:47 作者:不想活又不敢死

我实现一个AJAX自动完成/自动提示功能,而不是只做我想做的事情是类似于用户输入的通常显示的建议,但我想,让用户做部分的完成,以节省打字。

I'm implementing a AJAX autocomplete/autosuggest feature, and not only do I want to do the usual show suggestions that are similar to what the user typed, but I'd like to let the user do partial completions to save typing.

所以,想象一下我的字典,它有这些值:青苹果,绿色梨,绿色水果,蓝天,碧水,蓝唤醒

So, imagine my dictionary has these values in it: "green apple", "green pear", "green fruit", "blue sky", "blue water", "blue wake".

如果在G,建议应该是青苹果,绿色梨,绿色水果,我想,让用户按下tab键什么的用户类型来更新自己的查询绿色,那么他们可以输入A,他们会得到完成,以青苹果。

If the user types in "g", the suggestions should be "green apple", "green pear", "green fruit", and I'd like to let the user hit TAB or something to update his query to "green ", then they could type "a" and they'd get completed to "green apple".

我想Linux shell命令行完成后,建模。

I'm trying to model this after linux shell command line completion.

你能推荐一个控制/脚本,这样做吗?或者修改/现有控制的定制?

Can you recommend a control/script that does this? Or a modification/customization of an existing control?

推荐答案

不支持流行的自动完成插件(jQuery的,Scripty ...)自动完成这种特定类型的,因为通常是为选择提供一个下拉式的用户界面想要的比赛。

This specific type of autocompletion isn't supported in popular autocompletion plugins (for jQuery, Scripty...) because usually those provide a drop-down UI for choosing the wanted match.

因此​​,让我们假设,我们还没有得到出的现成的解决方案。嘘浩。能有多难是$ C C起来$?

So let's suppose we haven't got an out-of-the-box solution. Boo-ho. How hard can it be to code it up?

// 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)
}

这里 测试页面 - 它应该在正常的浏览器。对于支持IE浏览器使用的事件从的prototype.js,jQuery的或听等。

Test page here — it should work in normal browsers. For supporting IE use event listening from prototype.js, jQuery or other.