在下拉列表中有效地获取所选选项(XHTML Select元素) [英] Efficiently get selected option in a drop-down list (XHTML Select element)
问题描述
背景
使用XHTML Select元素的下拉列表中有很多选项(数十个).
使用JavaScript,我需要检索选定的选项.
问题
当前,我正在使用jQuery :selected
CSS选择器,它可以按预期工作,但是这种方法效率不高,因为它需要一段时间才能找到选定的选项-显然,这取决于CPU的能力客户端计算机,但在具有4GB RAM的体面的Intel Core 2中,性能会受到极大的损害.
问题
无论是使用jQuery还是普通的JavaScript和DOM,我都需要以有效的方式获取此XHTML Select元素的选定选项.
谢谢.
应尽可能简单:
//假设"select"是指select DOM元素var selectedElement = select.options [select.selectedIndex];
请参见 HTMLSelectElement [MDN] ./p>
更新:
在支持以下方法的新型浏览器(它们是 HTML5 的一部分)中,您也可以使用:
var selectedElement = select.item(select.selectedIndex);//或者var selectedElement = select [select.selectedIndex];//或者var selectedElement = select.selectedOptions [0];
Background
There's a large list of options - dozens - in a drop-down list using an XHTML Select element.
Using JavaScript, I need to retrieve the selected option.
Problem
Currently I'm using jQuery :selected
CSS selector and it works as expected, but this approach isn't efficient as it takes a while to find selected option - obviously, it depends on CPU power of client machine, but in a decent Intel Core 2 with 4GB of RAM, there's an excesive performance penalty.
Issue
Either using jQuery or plain JavaScript and DOM, I need to get selected option of this XHTML Select element in an efficient way.
Thank you in advance.
Should be as easy as:
// assuming `select` refers to the select DOM element
var selectedElement = select.options[select.selectedIndex];
Update:
In newer browsers which support the following methods (they are part of HTML5), you could also use:
var selectedElement = select.item(select.selectedIndex);
// or
var selectedElement = select[select.selectedIndex];
// or
var selectedElement = select.selectedOptions[0];
这篇关于在下拉列表中有效地获取所选选项(XHTML Select元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!