使用DOM引用下拉菜单中的选定项

时间:2023-01-19 08:35:06

Is there a way to reference a selected item from a dropdown menu implemented using select besides by index number? For instance, I would like a javascript function that does something like:

有没有办法从下拉菜单中引用所选项目,使用select除了索引号码?例如,我想要一个javascript函数,它可以执行以下操作:

if (document.getElementById("My_Select_Menu").selectedIndex.value == "Blue")
{
  do something;
}

but selectedIndex seems to return only a reference number to the first selected item. It seems like there should be a way to reference the value of the selected item, am I missing it?

但selectedIndex似乎只返回第一个选定项目的参考号。似乎应该有一种方法来引用所选项目的价值,我错过了吗?

3 个解决方案

#1


3  

Try:

尝试:

var sel = document.getElementById("My_Select_Menu");
if (sel.options[sel.selectedIndex].value == "Blue") {
    // do something
}

selectedIndex returns the offset of the selected option (as an integer) so you need to use that to grab the actual element from options of the <select>.

selectedIndex返回所选选项的偏移量(作为整数),因此您需要使用它来从

Demo.

演示。

#2


0  

You can include JQuery and use this to do what you want:

您可以包含JQuery并使用它来执行您想要的操作:

if($('#My_Select_Menu').val()=='Blue')
{
 ...
 }

http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

#3


0  

If all the options in the select have a value attribute or property set, then simply:

如果select中的所有选项都设置了value属性或属性,那么只需:

if (document.getElementById("My_Select_Menu").value == "Blue")

will do for all browsers since IE and Navigator 4.

自IE和Navigator 4以来,它将适用于所有浏览器。

#1


3  

Try:

尝试:

var sel = document.getElementById("My_Select_Menu");
if (sel.options[sel.selectedIndex].value == "Blue") {
    // do something
}

selectedIndex returns the offset of the selected option (as an integer) so you need to use that to grab the actual element from options of the <select>.

selectedIndex返回所选选项的偏移量(作为整数),因此您需要使用它来从

Demo.

演示。

#2


0  

You can include JQuery and use this to do what you want:

您可以包含JQuery并使用它来执行您想要的操作:

if($('#My_Select_Menu').val()=='Blue')
{
 ...
 }

http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

#3


0  

If all the options in the select have a value attribute or property set, then simply:

如果select中的所有选项都设置了value属性或属性,那么只需:

if (document.getElementById("My_Select_Menu").value == "Blue")

will do for all browsers since IE and Navigator 4.

自IE和Navigator 4以来,它将适用于所有浏览器。