javascript - 在 jQuery UI 可选中启用 Shift-Multiselect

标签 javascript jquery jquery-ui multi-select jquery-ui-selectable

我想通过按住 shift 在 jQuery UI 可选择表中启用多选功能。

如果在鼠标单击时按住 shift,我可能应该这样做

  • 获取最上面的选定元素
  • 获取被点击的元素
  • 选择其间的所有元素

但我找不到如何以干净的方式做到这一点......

目前我在可选配置中得到了这个:

start: function(e)
        {
            var oTarget = jQuery(e.target);
            if(!oTarget.is('tr')) oTarget = oTarget.parents('tr');
        }

所以 oTarget 是被点击的元素(而 e.currentTarget 是整个表格),但是现在怎么办?我怎样才能找到哪些元素已经被选择,从而可以告诉我单击的元素是在所选元素之上还是之下,并选择之间的所有元素?

我现在已经像这样解决了它,添加到可选择元素中:

jQuery(table).mousedown(function(e)
    {
        //Enable multiselect with shift key
        if(e.shiftKey)
        {
            var oTarget = jQuery(e.target);
            if(!oTarget.is('.ui-selectee')) oTarget = oTarget.parents('.ui-selectee');

            var iNew = jQuery(e.currentTarget).find('.ui-selectee').index(oTarget);
            var iCurrent = jQuery(e.currentTarget).find('.ui-selectee').index(jQuery(e.currentTarget).find('.ui-selected'));

            if (iCurrent < iNew) {
                iHold = iNew;
                iNew = iCurrent;
                iCurrent = iHold;
            }

            if(iNew != '-1')
            {
                jQuery(e.currentTarget).find('.ui-selected').removeClass('ui-selected');
                for (i=iNew;i<=iCurrent;i++) {
                    jQuery(e.currentTarget).find('.ui-selectee').eq(i).addClass('ui-selected');
                }
                e.stopImmediatePropagation();
                e.stopPropagation();
                e.preventDefault();
                return false;
            }
        }
    }).selectable(...)

最佳答案

您可以在没有插件的情况下做到这一点,如下所示:

var prev = -1; // here we will store index of previous selection
$('tbody').selectable({
    selecting: function(e, ui) { // on select
        var curr = $(ui.selecting.tagName, e.target).index(ui.selecting); // get selecting item index
        if(e.shiftKey && prev > -1) { // if shift key was pressed and there is previous - select them all
            $(ui.selecting.tagName, e.target).slice(Math.min(prev, curr), 1 + Math.max(prev, curr)).addClass('ui-selected');
            prev = -1; // and reset prev
        } else {
            prev = curr; // othervise just save prev
        }
    }
});

这是现场演示:http://jsfiddle.net/mac2000/DJFaL/1/embedded/result/

关于javascript - 在 jQuery UI 可选中启用 Shift-Multiselect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374743/

相关文章:

javascript - 在javascript拆分函数中拆分数组元素

JQuery 数据表和 ASP.NET UpdatePanel

javascript - Jquery UI 可排序在停止时调用两个函数

javascript - jQuery UI - .toogleClass() 不工作

jquery-ui - 如何在扩展功能中将参数传递给jquery UI对话框按钮功能?

jquery - 使用 jQuery 覆盖进度条

javascript - 在 For 循环变量上下文中使用不同的字母 - Javascript

php - 如何更改动态生成的内容 Javascript 和 PHP 的可见性

javascript - 使用 Angularjs 获取 token

javascript - 风 sails JS。无法从 POST 表单返回 'create'