Chosen 的 optgroup 第一级单击的时候选择二级的全部

相关环境 及 版本

Chosen (v1.6.2) https://harvesthq.github.io/chosen/

jQuery (v1.8.3) 官网 http://jquery.com/

  前几天用到了二级的多选列表,选择使用Chosen。如下图一个美化控件。

  问题1来了:客户要求在第一级单击的时候,要选择二级的全部。

  初步预想:chosen是没有这个功能的,用js给这个元素 加入一个click事件,然后遍历一下它的子元素应该就可以搞定了。

    好了开始按着这个思路处理。但发现很多不是想预想的那样,添加上事件后没有任何反应。来看看这个控件的显示原理吧,一看才发现它把原生的select元素隐藏,然后在元素后面添加了div元素并结合一些css样式才显示成我们看到的样子。一头雾水,还是百度一下吧,其它人应该也会遇到这个问题。果不其然,被我找到了 http://robido.com/jquery/add-selectdeselect-optgroup-click-events-harvests-chosen-jquery-plugin/ 不过是英文的,凑合着看吧。

 1 // Add select/deselect all toggle to optgroups in chosen
 2 $(document).on('click', '.group-result', function() {
 3     // Get unselected items in this group
 4     var unselected = $(this).nextUntil('.group-result').not('.result-selected');
 5     if(unselected.length) {
 6         // Select all items in this group
 7         unselected.trigger('mouseup');
 8     } else {
 9         $(this).nextUntil('.group-result').each(function() {
10             // Deselect all items in this group
11             $('a.search-choice-close[data-option-array-index="' + $(this).data('option-array-index') + '"]').trigger('click');
12         });
13     }
14 });

  测试了一下还不错,和客户的需求吻合。

  使用一段时间以后,由于业务扩展 需要在这个页面上面增加一个二级多选列表。那就再加一个select元素,还用chosen呗,结果发现了一个致命问题。

问题2来了:取消选择,也就是代码中deselect all 的时候,jquery的选择器选择的是整个document的。删除两个select元素中相同索引的子元素,造成数据丢失。

  经过一思索后,改进如下。

 1 // Add select/deselect all toggle to optgroups in chosen
 2     $( document ).on( 'click', '.group-result', function () {
 3         // Get unselected items in this group
 4         var unselected = $( this ).nextUntil( '.group-result' ).not( '.result-selected' );
 5         if ( unselected.length ) {
 6             // Select all items in this group
 7             unselected.trigger( 'mouseup' );
 8         } else {
 9             var groups = new Array();
10             $( this ).nextUntil( '.group-result' ).each( function () {
11                 // Deselect all items in this group
12                 // $( 'a.search-choice-close[data-option-array-index="' + $( this ).data( 'option-array-index' ) + '"]' ).trigger( 'click' );
13                 groups[groups.length] = $(this).parent().parent().prev().find('a.search-choice-close[data-option-array-index="' + $( this ).data( 'option-array-index' ) + '"]');
14             } );
15 
16             for (var i = groups.length - 1; i >= 0; i--) {
17                 groups[i].trigger('click');
18             }
19         }
20     } );

注意:trigger('click')后会删除本身,所以要先循环一遍 找到所有需要移除的元素,再全部触发删除。

原文地址:https://www.cnblogs.com/h2285409/p/6903626.html