如何自动过滤 HTML 选择列表?
我有一个 HTML 选择列表,其中包含相当多(1000 多个)名称。 我有一个 JavaScript,如果有人开始输入,它将选择第一个匹配的名称。 此匹配查看项目的开头:
var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = dropdownlist.options[n].text;
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
{
dropdownlist.selectedIndex = n;
return false;
}
}
客户希望有建议或自动过滤器:输入名称的一部分应该“找到”包含该部分的所有名称。 我见过一些类似 Google Suggest 的选项,大多数使用 Ajax,但我想要一个纯 JavaScript 选项,因为选择列表已经加载了。 有人指点一下吗?
I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:
var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = dropdownlist.options[n].text;
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
{
dropdownlist.selectedIndex = n;
return false;
}
}
The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更改
为
在
optionText
中的任意位置查找dropdownlist.keypressBuffer
。Change
to
To find
dropdownlist.keypressBuffer
anywhere in theoptionText
.YUI 库有一个用于此类功能的库,称为 AutoComplete。
AutoComplete 的数据源可以是本地 javascript 对象,或者如果您改变主意也可以轻松切换到 Ajax。
YUI 组件具有相当多的功能,可高度定制。
编辑:我不确定您是否可以按照问题的要求让它与选择框一起使用。 也许有可能。
The YUI libraries have a library for this sort of functionality, called AutoComplete.
The DataSource for AutoComplete can be local javascript objects, or can be easily switched to Ajax if you change your mind.
The YUI components are pretty customizable with a fair bit of functionality.
Edit: I'm not sure if you can get it to work with a select box as required by the question though. Might be possible.
我会设置一个缓存来保存我的
select
中的options
。 我不会在select
中过滤options
,而是清除select
,并用匹配的options
重新填充它>。伪代码丰富:
这是我写的一个小 POC,对另一个
select
中选择的内容进行过滤 - 实际上将一堆选择链接在一起。也许它可以给你一些想法:
I would set up a cache to hold the
options
inside myselect
. And instead of filteringoptions
in theselect
, I would clear theselect
, and re-populate it with matchedoptions
.Pseudo-code galore:
Here's a little POC I wrote, doing filtering on
selects
from what is selected in anotherselect
--in effect chaining a bunch of selects together.Perhaps it can give you a few ideas:
使用这个过滤脚本
http://www.barelyfitz.com/projects/filterlist/
use this filter script
http://www.barelyfitz.com/projects/filterlist/