我有一个<select>.使用JavaScript,我需要从选项列表中获取特定的<option>,而我所知道的只是选项的值.可以选择也可以不选择该选项.
这是一个问题:有成千上万的选项,我需要在循环中做几百次.现在我遍历"选项"数组并寻找我想要的选项.这太慢了(从某种意义上说,在我的快速机器上,浏览器锁定,直到我在几分钟后将其杀死).
有没有更快的方法来做到这一点?我将采用特定于浏览器的方式,但当然DOM标准的方式会很好.
我这样做:
// first, build a reverse lookup
var optCount = mySelect.options.length;
var reverseLookup = {};
for (var i = 0; i < optCount; i++)
{
var option = mySelect.options[i];
if (!reverseLookup[option.value])
{
// use an array to account for multiple options with the same value
reverseLookup[option.value] = [];
}
// store a reference to the DOM element
reverseLookup[option.value].push(option);
}
// then, use it to find the option
var foundOptions = reverseLookup["Value that you are looking for"];
if (foundOptions && foundOptions.length)
{
alert(foundOptions[0].id);
}
Run Code Online (Sandbox Code Playgroud)