【问题标题】:Select multiple options in JS在JS中选择多个选项
【发布时间】:2014-05-26 11:23:46
【问题描述】:

我有以下看法:

<ul id="entries_list">
 <li>a</li>
 <li>b</li>
 <li>c</li>
</ul>

我想使用 shift 进行多选。当用户按住 shift 并单击第一个和第三个 li 时,将选择所有 li。我试过 Jquery 可选择的:

prev = -1;
$("#entries_list").selectable({
  filter:'li',
  selecting: (e, ui) ->
    curr = $(ui.selecting.tagName, e.target).index(ui.selecting);
    if(e.shiftKey && prev > -1)
      $(ui.selecting.tagName, e.target).slice(Math.min(prev, curr), 1 + Math.max(prev, curr)).addClass('custom_selected');
      prev = -1;
    else
      prev = curr;

但问题是我必须使用自定义类“custom_selected”。在上述情况下,它使用 shift 正确选择但没有取消选择。 Jquery 添加自己的类。是否可以覆盖默认类?如果我可以使用自定义类会更容易。

编辑:

我有这个,但它工作不正确:

http://jsfiddle.net/DJFaL/25/

编辑2:

我真的很抱歉,但我粘贴了错误的 jsfiddle 赞。现在是正确的。

【问题讨论】:

  • 你为什么不用&lt;select multiple&gt;
  • 添加jsfiddle 以获得更好的帮助并添加完整的 jquery 而不仅仅是一个片段,没有人可以帮助...
  • 我不知道什么不起作用...一切正常...你有什么浏览器

标签: jquery multi-select selectable


【解决方案1】:

为什么不直接使用select with multiple attribute?或者简单的 jQuery 用于您的代码? 无论如何,对于 jQuery,我为您创建了一个演示:

http://jsfiddle.net/lotusgodkk/DJFaL/26/

JS:

$('#entries_list li').on('click', function (e) {
    var li = $(this);
    var shift = e.shiftKey;
    if (shift) {
        if (li.hasClass('selected')) {
            li.removeClass('selected');
        } else {
            li.addClass('selected');
        }

    } else {
        $('.selected').removeClass('selected');
        li.addClass('selected');
    }
    var array = jQuery('#entries_list li.selected').map(function () {
        return $(this).text();
    }).get();
    $('p').text(array.join(','));
});

CSS:

.selected {
    background-color:#eee;
}
ul {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: moz-none;
    -ms-user-select: none;
    user-select: none;
}

HTML:

<ul id="entries_list">
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>dc</li>
    <li>ddvc</li>
    <li>cvb</li>
    <li>gc</li>
    <li>cdf</li>
    <li>cd5</li>
</ul>Selected li:
<p></p>

默认情况下,我在 li 中使用 text,你可以将数组中的 $(this).text() 映射到任何其他属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2019-08-22
    • 2022-07-16
    • 1970-01-01
    • 2015-03-21
    • 2014-12-23
    相关资源
    最近更新 更多