使用 jQuery 取消选择选定区域

Deselect a selected area with jQuery

本文关键字:区域 选择 jQuery 取消 使用      更新时间:2023-09-26

我有以下 HTML:

<div class="folders block">
    <div class="ui-widget-content">            
         <table class="folders-list">
             <tbody class="folder">
                  <tr><td style="text-align: center">Папки: </td></tr>
                  <tr class="folder-name"><td><i class="fa fa-folder-open"></i><span>Всички</span></td></tr>          
             </tbody>
         </table>
    </div>
</div>

以及以下 jQuery:

$(".folder").selectable({
    stop: function() {
        $(".ui-selected", this)
            .each(function() {
                var index = $("table tbody").index(this);   
            });     
    }
});

当我想取消选择所选项目时,一切都很好接受。无论我在哪里点击,什么都不会发生。我没有找到任何可以提供帮助的东西。

如果我理解正确,没有直接的方法可以做到这一点,但您可以使用技巧。

当用户单击容器(.folder)外的某个位置时,您应该做两件事:

  1. 删除选定项的.ui-selected类。
  2. 清除小组件实例的选定列表。

注意:这是一个通用解决方案,所以它可能会与您的其他代码(例如$('html').click)冲突,所以要小心。

到代码:

$( "#selectable" ).selectable().click(function(event) {
  event.stopPropagation();
});
$('html').click(function(){
  var ins = $( "#selectable" ).selectable( "instance" );
  // clear the selected list
  ins.selectees = [];
  // remove the selected class
  ins.element.find('.ui-selected').removeClass('ui-selected');
});
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<ol id="selectable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
  <li class="ui-widget-content">Item 4</li>
  <li class="ui-widget-content">Item 5</li>
  <li class="ui-widget-content">Item 6</li>
  <li class="ui-widget-content">Item 7</li>
</ol>