今天我遇到了同样的问题。如果不删除不需要的选项,您将无法获得预期的结果。但问题是,如果您想稍后显示这些选项,则需要记住这些选项。
我的解决方案非常简单,适用于所有主流浏览器:
function filterList(oList, rxSearch)
{
// Create backup of the old option list (only once)
if(typeof(oList.tagOptions) === "undefined")
{
// Save current options
oList.tagOptions = [ ]; // Generate a dynamic property for this DOM object
for(var i = 0; i < oList.options.length; ++i)
oList.tagOptions.push(oList.options[i]);
}
// Clear the current option list
while(oList.options.length)
oList.options.remove(0);
// Add only those options which match the regular expression
for(var i = 0; i < oList.tagOptions.length; ++i)
{
if(rxSearch.test(oList.tagOptions[i].text))
oList.options.add(oList.tagOptions[i]);
}
}
诀窍是选项元素将在第一次运行时被复制到动态创建的 tagOptions 属性中。由于仍然会引用(在 tagOptions 中)这些已移除的选项 DOM 元素,因此它们不会被释放。此外,您不需要全局变量。稍后,可见选项 (oList.options) 将被清除,仅添加与搜索词匹配的选项。
使用以下 HTML 代码:
<select id="myList" size="10">
<option>apple</option>
<option>advocado</option>
<option>banana</option>
<option>coconut</option>
</select>
你可以这样称呼它:
filterList(document.getElementById("myList"), /^a/i); // Display only those elements, which start with an a
alert("Display all with a");
filterList(document.getElementById("myList"), /^b/i); // Display only those elements, which start with an b
alert("Display all with b");
filterList(document.getElementById("myList"), /^/i); // Display only those elements, which start with an c
alert("Display all");
我已经用 Firefox、Internet Explorer 11、Chrome 和 Opera 对此进行了测试。它适用于我的目的。
function filterList(oList, rxSearch)
{
// Create backup of the old option list (only once)
if(typeof(oList.tagOptions) === "undefined")
{
// Save current options
oList.tagOptions = [ ]; // Generate a dynamic property for this DOM object
for(var i = 0; i < oList.options.length; ++i)
oList.tagOptions.push(oList.options[i]);
}
// Clear the current option list
while(oList.options.length)
oList.options.remove(0);
// Add only those options which match the regular expression
for(var i = 0; i < oList.tagOptions.length; ++i)
{
if(rxSearch.test(oList.tagOptions[i].text))
oList.options.add(oList.tagOptions[i]);
}
}
filterList(document.getElementById("myList"), /^a/i); // Display only those elements, which start with an a
alert("Display all with a");
filterList(document.getElementById("myList"), /^b/i); // Display only those elements, which start with an b
alert("Display all with b");
filterList(document.getElementById("myList"), /^/i); // Display only those elements, which start with an c
alert("Display all");
<select id="myList" size="10">
<option>apple</option>
<option>advocado</option>
<option>banana</option>
<option>coconut</option>
</select>