【发布时间】:2014-07-08 14:50:44
【问题描述】:
我在选择元素中创建了一个 javascript 搜索。
选项标签没有得到任何隐藏或显示的 CSS,对于这个解决方案,我删除了不匹配的选项并为重置列表按钮的已删除选项进行备份。
它工作正常,但我有一个问题,这个选择列表有大约 19000 个选项。 搜索工作正常,但是当我点击重置按钮时,只有 19000 中的 9500 选项回来了。
感谢您的帮助。
代码如下:
HTML
<h1>Search in select "option" tag</h1>
<select multiple name="selectMenu" id="selectMenu" style="width:100px" size=10>
<option value ="item 1">item 1</option>
<option value ="item 2">item 2</option>
<option value ="thing 3">thing 3</option>
<option value ="item 4">item 4</option>
<option value ="stuff 5">stuff 5</option>
<option value ="stuff 6">stuff 6</option>
<option value ="stuff 7">stuff 7</option>
<option value ="item 8">item 8</option>
</select>
<p>Search within this list</p>
<input type=text name="search" id="search" onkeypress="searchItems();">
<br>
<input type=button value="Search" onclick="searchItems();">
<input type=button value="Reset List" onclick="resetList();">
Javascript
var itemList = null;
var itemListOriginal = new Array();
var backup = false;
function searchItems() {
itemList = document.getElementById("selectMenu");
var searchStrObj = document.getElementById("search");
var itemDescription = "";
// replace white space with wild card
var searchString = searchStrObj.value;
searchString = searchString.replace(" ", ".*");
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag
if (itemListOriginal.length < 1)
backup = true;
else
backup = false;
// loop through options and check for matches
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemDescription = itemList.options.item(i).text;
if (backup) {
hash = new Array();
hash['name'] = itemDescription;
hash['value'] = itemList.options.item(i).value;
itemListOriginal[i] = hash;
}
if (!itemDescription.match(re)) {
itemList.remove(i);
}
}
return false;
}
function resetList() {
//hack! remove all elements from list before repopulating
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemList.remove(i);
}
for (i=0; i < itemListOriginal.length; i++) {
hash = itemListOriginal[i];
//option = new Option(hash['name'], hash['value']); REMOVED
//itemList.options.add(option, i); REMOVED
itemList.options[i] = new Option(hash['name'], hash['value'], false, false);
}
document.getElementById("search").value = "";
}
【问题讨论】:
-
从下次开始,请在 SO 上包含您的代码,而不是附加链接。
-
抱歉,代码很长,因为隐藏了一些代码,所以很难在此处添加。
-
是的,请!因为我正在编辑其他内容,所以我已经为你添加了它。
-
哇,太好了,谢谢。
-
为什么不简单地隐藏/显示选项?
标签: javascript jquery search html-select removechild