如何使用 jQuery 在多选中切换选项的选择? [英] How to toggle selection of an option in a multi-select with jQuery?

查看:39
本文介绍了如何使用 jQuery 在多选中切换选项的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标准的select multiple HTML 输入字段,例如:

I have a standard select multiple HTML Input field, for example:

<select multiple="multiple" size="5" id="mysel" name="countries"> 
    <option value="2">Afghanistan</option> 
    <option value="4">Aland</option> 
</select>

由于这是一个多选,要选择多个值,您必须按住 CTRL 键并选择任何其他元素.但是我想要实现的是:

As this is a multi-select, to select more than one value you have to hold the CTRL key and select any further elements. However what I want to achieve is, that:

  1. 点击一个 UNSELECTED 选项将其选中
  2. 单击已选择的选项将取消选择它.

这个想法是为了避免必须按下 CTRL 键并更改此输入字段的用法语义.元素只能通过点击来选择和不可选择(即切换选择状态).

The idea is to avoid having to press the CTRL key and change the usage semantics of this input field. Elements should only be selectable and un-selectable by clicking (ie. toggling of the select status).

我还没有能够实现这一点.伪代码应该是这样的.

I have not yet been able to implement this. The pseudo-code should look something like this.

  1. 捕捉一个 Click 事件.
  2. 检查被点击的元素是否未被选中,然后选中
  3. 或者,如果被点击的元素被选中,则取消选中它.

我应该如何实施?

推荐答案

你可以使用下面的代码片段来达到你想要的效果

You may use the following snippet to achieve your desired effect

$("select[multiple] option").mousedown(function(){
   var $self = $(this);

   if ($self.prop("selected"))
          $self.prop("selected", false);
   else
       $self.prop("selected", true);

   return false;
});

在旧版本的 jQuery 中,prop() 不可用:

In older versions of jQuery, where prop() was not available:

$("select[multiple] option").mousedown(function(){
   var $self = $(this);

   if ($self.attr("selected"))
          $self.attr("selected", "");
   else
       $self.attr("selected", "selected");

   return false;
});

这篇关于如何使用 jQuery 在多选中切换选项的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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