如何使 HTML 多选行为就像始终按住控制按钮一样 [英] How can I make an HTML multiple select act like the control button is held down always

查看:24
本文介绍了如何使 HTML 多选行为就像始终按住控制按钮一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在处理的网络应用程序,它需要一个 HTML 多选元素,就像一直按住控制键一样.IE.点击一个选项会切换它是否被选中.

I have a web application I'm working on that requires a HTML multiple select element operates like the control key is held down at all times. I.e. click on an option will toggle whether it is selected or not.

我尝试了各种 Jquery 事件绑定,但似乎标准 HTML 多选行为在 Jquery 绑定事件触发之前执行,这使得简单地拦截事件并修改标准行为几乎是不可能的.

I have tried various Jquery event binds but it appears that the standard HTML multiple select behavior executes before the Jquery bound event fires, making it all but impossible to simply intercept the event and modify the standard behavior.

我怎样才能使单击可以切换单个选项的选择?

How can I make is so that single clicks will toggle the selection of an individual option?

推荐答案

试试这个.您可以将选项值存储在对象中,然后使用单击操作更新对象,然后将更改应用于选择.

Try this out. You can store the option values in an object and use the click action to update the object then apply the changes to the select.

演示

http://jsfiddle.net/iambriansreed/BSdxE/

HTML

<select class="select-toggle" multiple="multiple">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>​

JavaScript

$('.select-toggle').each(function(){    
    var select = $(this), values = {};    
    $('option',select).each(function(i, option){
        values[option.value] = option.selected;        
    }).click(function(event){        
        values[this.value] = !values[this.value];
        $('option',select).each(function(i, option){            
            option.selected = values[option.value];        
        });    
    });
});​

这篇关于如何使 HTML 多选行为就像始终按住控制按钮一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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