2014-09-02 67 views
3

我使用的是用这个代码的StackOverflow发布多选框没有按住Ctrl键单击

How to avoid the need for ctrl-click in a multi-select box using Javascript?

还建议在许多其他文章,做多项选择,而不按Ctrl键。

代码:

$('option').mousedown(function(e) { 
    e.preventDefault(); 
    $(this).prop('selected', !$(this).prop('selected')); 
    return false; 
}); 

的问题是,代码是不工作的火狐31.0。 您可以通过下面的链接

FIDDLE

没有任何人知道一个解决有关此问题的尝试:)

+0

IM多选插件的jQueryUI的http://www.erichynds.com/blog/jquery-ui-multiselect-widget的忠实粉丝,这也将让人们进行筛选,并有选择“选择全部'选项 – haxxxton 2014-09-02 08:41:04

+0

感谢您的评论,实际上,我不需要使用新图书馆就可以找到问题:) – user3584625 2014-09-02 08:47:13

+0

您是否尝试使用鼠标的滚动按钮单击选项? :D实际上它不需要CTRL被按下 – 2014-09-02 09:38:54

回答

1

下面的代码在Firefox 31.0,IE 10和克罗默36.0.1985.143。但如果使用CTRL键,它也不能很好地工作。

$('select').bind("click", function (event, target) { 

     event.preventDefault(); 
     var CurrentIndex = event.target.selectedIndex==undefined? $(event.target).index(): event.target.selectedIndex 
     var CurrentOption = $("option:eq(" + CurrentIndex+ ")", $(this)); 
     if ($(CurrentOption).attr('data-selected') == undefined || $(CurrentOption).attr('data-selected') == 'false') { 
      $(CurrentOption).attr('data-selected', true); 
     } 
     else { 
      $(CurrentOption).prop('selected', false).attr('data-selected', false); 
     } 

     $("option", $(this)).not(CurrentOption).each(function (Index, OtherOption) { 
      $(OtherOption).prop('selected', ($(OtherOption).attr('data-selected') == 'true') ? true : false); 
     }); 
     return false; 
    }); 
+0

您可以测试是否按下Ctrl或Meta键。我也相信它是'.on',不再是'.bind' – mplungjan 2014-09-02 12:09:48

+0

感谢您的评论, 有一个简单的问题,但我不知道在哪里。 如果选择以某些选定选项开始,如下所示: 现在如果您尝试选择其他选项,它总是清除已经选定。 – user3584625 2014-09-02 13:31:00

+0

@ user3584625我已经使用了一个自定义属性data-selected来跟踪其状态,因此您还需要维护该属性。因此,当您正在选择选项时,请将该属性也设置为true。 – Priyank 2014-09-03 04:40:12

相关问题