在多个下拉列表中获取单击选项 [英] Get clicked option in multiple dropdown

查看:122
本文介绍了在多个下拉列表中获取单击选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多选下拉列表,例如:

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>

如果我然后选择选项#4 ,我怎么才能得到选项#4 而不是选项#2 选项#3 ?我知道我可以通过这个获得所有选择的选项:

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:

var selectedOptions = $("#myList option:selected");

但是我只想要我点击的选项 - 选项#4 。这可能吗?

However I only want the option I clicked - Opt #4. Is this possible?

编辑:请注意,当我在更改事件中操作列表时,我无法做到它在中单击事件。还添加了缺失的多个。

note that as I manipulate the list inside a change event I can't do it in a click event. Also added missing multiple.

推荐答案

您可以在每个选项元素的点击处理程序中获取它:

You can get it in the click handler for each option element:

$("#myList option").click(function() {
    var clickedOption = $(this);
});






更新


编辑:当我在更改事件中操作列表时,我无法在点击事件中执行此操作。

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:

$("#myList").on("click", "option", function() {
    var clickedOption = $(this);
});

但有一点需要注意的是选项元素不会在IE中点击点击事件,因此上述两种情况都不适用于该浏览器。

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.

这篇关于在多个下拉列表中获取单击选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆