有没有快速的方法可以使用JavaScript从<select>按值获取<option>?</select> </option>

时间:2008-11-07 12:16:26

标签: javascript html

我有一个&lt; select&gt;。使用JavaScript,我需要获得特定的&lt;选项&gt;从选项列表中,我所知道的是选项的价值。可以选择也可以不选择该选项。

这是一个问题:有成千上万的选项,我需要在循环中做几百次。现在我遍历“选项”数组并寻找我想要的选项。这太慢了(从某种意义上说,在我的快速机器上,浏览器锁定,直到我在几分钟后将其杀死)。

有没有更快的方法呢?我将采用特定于浏览器的方式,但当然以DOM标准的方式会很好。

8 个答案:

答案 0 :(得分:7)

我会这样做:

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

答案 1 :(得分:2)

我建议您在选择中没有数千个选项。

也许你可以用不同的方式构建你的数据,对我来说有数千个条目的选择似乎是错误的。

也许你的应用需要这个,但这不是这个元素的典型用法。

答案 2 :(得分:1)

这是Tomalak的一个小调速的答案。您会看到迭代的while循环比迭代的for循环更快。 (我很懒,所以我不提供链接。)

var i = mySelect.options.length - 1;
var reverseLookup = {};
while ( i >= 0 )
{
  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);
  i--;
}

// then, use it to find the option
var foundOptions = reverseLookup["Value that you are looking for"];
if (foundOptions && foundOptions.length)
{
  alert(foundOptions[0].id);
}

答案 3 :(得分:0)

不,没有,你真的是最好的方式。您可以尝试更快速查找的唯一另一件事是为每个选项提供一个ID标记,以便您可以将它们作为DOM对象查找,而不是循环遍历DOM对象的子项。

答案 4 :(得分:0)

您可以遍历所有选项并将所有项目放入关联数组中。然后,您只需查找myOptions[valueImLookingFor]

我没有对此进行测试,也无法保证它会更快/更好。但它应该摆脱所有这些循环。

根据您的设置和需求,您还可以在客户端生成一个javascript数组,并将其放在标记中,而不是(或者除了)选择之外。

答案 5 :(得分:0)

我的建议是查看像Dojo and its way of selecting DOM nodes这样的框架/工具包。

该工具包可以解决很多浏览器的不一致问题,并允许您快速轻松地选择和操作DOM节点。

答案 6 :(得分:0)

我认为这可能表明选择中“数千”的项目可能不是最好的用户体验。也许您应该考虑尝试将下拉菜单限制为几个,以便在用户选择结果时缩小结果范围。

答案 7 :(得分:-1)

使用jQuery这样的事情会更快:

$("#idselect option[value='yourval']")

http://docs.jquery.com/Selectors/attributeEquals#attributevalue

相关问题