Javascript 如何使用Javascript而不是JQuery获取选定的选项ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12625516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:52:48  来源:igfitidea点击:

How to get selected option ID with Javascript not JQuery

javascripthtmlselect

提问by yorgos

I need to print the selected option ID with Javascript not JQuery for both select tags.

我需要使用 Javascript 而不是 JQuery 为两个选择标签打印选定的选项 ID。

Assume we have more than one select tags.

假设我们有多个选择标签。

<select  onchange="showOptions(this)" id="my_select1">
   <option value="a1" id="ida1">Option1</option>
   <option value="a2" id="ida2">Option2</option>
</select>

<select  onchange="showOptions(this)" id="my_select2">
   <option value="b1" id="idb1">Option1</option>
   <option value="b2" id="idb2">Option2</option>
</select>

I found out the following way options[selectedIndex].idbut how can I know to which one of those that line refers to..

我发现了以下方式,options[selectedIndex].id但我怎么知道那条线指的是哪一个..

Any suggestions?

有什么建议?

I Tried the following but it did not work.

我尝试了以下但没有奏效。

<select id="my_select" onchange="showOptions2(this)">
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>


<script type = "text/javascript">


function showOptions2(s){
 var adVALUE = console.log(s[s.selectedIndex].value); // get value
 var adID = console.log(s[s.selectedIndex].id); // get id

  alert(adID);

}
</script>

回答by Fabrizio Calderan

<select onchange="showOptions(this)">
   ...


this function will do the work

此功能将完成工作

function showOptions(s) {
  console.log(s[s.selectedIndex].value); // get value
  console.log(s[s.selectedIndex].id); // get id
}

Note that, unless you are using them for other purpose, you may omit the idon selectelements

请注意,除非您将它们用于其他目的,否则您可以省略idonselect元素

Example jsbin : http://jsbin.com/adopiz/2/edit

示例jsbin:http://jsbin.com/adopiz/2/edit