javascript 在多个下拉菜单中获取点击选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10431381/
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
Get clicked option in multiple dropdown
提问by Frets
I have a multi select dropdown eg:
我有一个多选下拉菜单,例如:
<select id="myList" multiple="multiple">
<option value="1">Opt #1</option>
<option value="2" selected="selected">Opt #2</option>
<option value="3" selected="selected">Opt #3</option>
<option value="4">Opt #4</option>
</select>
If I then selects Opt #4
, how do I then only get Opt #4
and not Opt #2
and Opt #3
? I know I can get all selected options by this:
如果我然后选择Opt #4
,那么我如何只得到Opt #4
而不是Opt #2
和Opt #3
?我知道我可以通过以下方式获得所有选定的选项:
var selectedOptions = $("#myList option:selected");
However I only want the option I clicked - Opt #4
. Is this possible?
但是我只想要我点击的选项 - Opt #4
。这可能吗?
Edit: note that as I manipulate the list inside a change
event I can't do it in a click
event. Also added missing multiple.
编辑:请注意,当我在change
事件中操作列表时,我无法在click
事件中进行操作。还添加了缺失的多个。
回答by Rory McCrossan
You can get it in the click handler for each option element:
您可以在每个选项元素的点击处理程序中获取它:
$("#myList option").click(function() {
var clickedOption = $(this);
});
Update
更新
EDIT: As I manipulate the list inside a change event, I can't do it in a click event.
编辑:当我在更改事件中操作列表时,我无法在单击事件中执行此操作。
In that case you need to delegate the event using on
. Try this:
在这种情况下,您需要使用on
. 试试这个:
$("#myList").on("click", "option", function() {
var clickedOption = $(this);
});
One thing to note, however, is that option
elements will not raise click
events at all in IE, so neither of the above will not work in that browser.
然而,需要注意的一件事是,option
元素click
在 IE 中根本不会引发事件,因此上述两种方法在该浏览器中都不起作用。
回答by sv_in
As you know, If the user clicked on opt #4 without Cntrl key pressed, then you will only get Opt#4 as the selected option.
如您所知,如果用户在没有按下 Cntrl 键的情况下单击了选项 #4,那么您将只会获得选项 #4 作为所选选项。
If the user clicked on opt #4 with Cntrl key pressed, then all three options will be selected. So all three options will be returned. If you want only Opt#4, then you would need to add a click event handler.
如果用户在按下 Cntrl 键的情况下单击选项 #4,则将选择所有三个选项。所以所有三个选项都将被返回。如果您只想要 Opt#4,那么您需要添加一个点击事件处理程序。
回答by Daniel Baulig
Would something like the following help you?
以下内容对您有帮助吗?
$('#myList').delegate('option', 'click', function (opt) {
alert('Option ' + opt.value + ' was clicked');
});