有什么快速的方法来获得< option>从< select>按价值,使用JavaScript? [英] Is there any fast way to get an <option> from a <select> by value, using JavaScript?

查看:64
本文介绍了有什么快速的方法来获得< option>从< select>按价值,使用JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< select> ;.使用JavaScript,我需要获得一个特定的< option>从选项列表中,我所知道的是选项的价值。这个选项可能会也可能不会被选中。



这里有一个问题:有成千上万个选项,我需要循环执行几百次。现在我循环访问options数组并查找我想要的选项。这太慢了(在我的速度非常快的机器上,浏览器被锁定,直到我在几分钟后杀死它)。

有没有更快的方法可以做这个?我会采取特定于浏览器的方式,但当然一个DOM标准的方式会很好。 它是这样的:

  //首先,构建反向查找
var optCount = mySelect.options.length;
var reverseLookup = {};
for(var i = 0; i< optCount; i ++)
{
var option = mySelect.options [i];
if(!reverseLookup [option.value])
{
//使用一个数组来解释具有相同值的多个选项
reverseLookup [option.value] = [] ;
}
//存储对DOM元素的引用
reverseLookup [option.value] .push(option);
}

//然后,使用它来查找选项
var foundOptions = reverseLookup [您要查找的值];
if(foundOptions& foundOptions.length)
{
alert(foundOptions [0] .id);
}


I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.

Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).

Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.

解决方案

I'd do it like this:

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

这篇关于有什么快速的方法来获得&lt; option&gt;从&lt; select&gt;按价值,使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆