如何使用jQuery切换多选中选项的选择? [英] How to toggle selection of an option in a multi-select with jQuery?
问题描述
我有一个标准的选择多个
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:
- 点击一个UNSELECTED选项将其选中
- 单击一个SELECTED选项取消选择。
这个想法是避免按 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.
- 捕获Click事件。
- 检查是否点击的元素未被选中,然后选择它
- 或者,如果点击元素被选中,则取消选择它。
我应该如何实现这一点?
How should I implement this?
推荐答案
您可以使用以下代码片段来实现您的期望效果
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屋!