Javascript 单击选项事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4670405/
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
Click on option event
提问by Upvote
how do I handle events for option elements?
如何处理选项元素的事件?
<select>
<option value='option1'>Gateway 1</option>
<option value='option2'>Gateway 2</option>
<option value='option3'>Gateway 3</option>
</select>
When an option element is clicked I want to display a little description for the element. Any ideas how to do that?
单击选项元素时,我想显示该元素的一些说明。任何想法如何做到这一点?
回答by JasCav
You're going to want to use jQuery's change event. I am displaying the text of your option as an alert, but you can display whatever you want based on your needs. (You can also, obviously, put it inside another part of the page...it doesn't need to be an alert.)
您将要使用 jQuery 的更改事件。我将您的选项文本显示为警报,但您可以根据需要显示任何内容。(显然,您也可以将其放在页面的另一部分中……它不需要是警报。)
$('#myOptions').change(function() {
var val = $("#myOptions option:selected").text();
alert(val);
});
Also, note, that I added an ID to your select
tag so that you can more easily handle events to it (I called it myOptions).
另外,请注意,我在您的select
标签中添加了一个 ID,以便您可以更轻松地处理它的事件(我将其称为 myOptions)。
Example: http://jsfiddle.net/S9WQv/
回答by niksvp
As specified by JasCavusing jQuery you can accomplish the same in javascript using
正如JasCav使用 jQuery指定的那样,您可以使用 javascript 在 javascript 中完成相同的操作
<select onchange="alert(this.options[this.selectedIndex].text);">
<option value='option1'>Gateway 1</option>
<option value='option2'>Gateway 2</option>
<option value='option3'>Gateway 3</option>
</select>
Alternatively, onclick event of option, but note that it is not compatible on all browsers.
或者,选项的 onclick 事件,但请注意它并非在所有浏览器上都兼容。
<select>
<option value='option1' onclick="alert(this.value);" >Gateway 1</option>
<option value='option2'>Gateway 2</option>
<option value='option3'>Gateway 3</option>
</select>