RowSelector.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. export default class RowSelector {
  2. constructor(options) {
  3. let _this = this;
  4. _this.options = $.extend({
  5. // checkbox css选择器
  6. checkboxSelector: '',
  7. // 全选checkbox css选择器
  8. selectAllSelector: '',
  9. // 选中效果颜色
  10. background: 'rgba(255, 255,213,0.4)',
  11. // 点击行事件
  12. clickRow: false,
  13. // 表格选择器
  14. container: 'table',
  15. }, options);
  16. _this.init()
  17. }
  18. init() {
  19. let options = this.options,
  20. checkboxSelector = options.checkboxSelector,
  21. $document = $(document),
  22. selectAll = options.selectAllSelector;
  23. $(selectAll).on('change', function() {
  24. let checked = this.checked;
  25. $.each($(this).parents(options.container).find(checkboxSelector), function (_, checkbox) {
  26. let $this = $(checkbox);
  27. if (! $this.attr('disabled')) {
  28. $this.prop('checked', checked).trigger('change');
  29. }
  30. });
  31. });
  32. if (options.clickRow) {
  33. $document.off('click', checkboxSelector).on('click', checkboxSelector, function (e) {
  34. if (typeof e.cancelBubble != "undefined") {
  35. e.cancelBubble = true;
  36. }
  37. if (typeof e.stopPropagation != "undefined") {
  38. e.stopPropagation();
  39. }
  40. });
  41. $document.off('click', options.container+' tr').on('click', options.container+' tr', function () {
  42. $(this).find(checkboxSelector).click();
  43. });
  44. }
  45. $document.off('change', checkboxSelector).on('change', checkboxSelector, function () {
  46. var tr = $(this).closest('tr');
  47. if (this.checked) {
  48. tr.css('background-color', options.background);
  49. if ($(checkboxSelector + ':checked').length === $(checkboxSelector).length) {
  50. $(selectAll).prop('checked', true)
  51. }
  52. } else {
  53. tr.css('background-color', '');
  54. }
  55. });
  56. }
  57. /**
  58. * 获取选中的主键数组
  59. *
  60. * @returns {Array}
  61. */
  62. getSelectedKeys() {
  63. let selected = [];
  64. $(this.options.checkboxSelector+':checked').each(function() {
  65. var id = $(this).data('id');
  66. if (selected.indexOf(id) === -1) {
  67. selected.push(id);
  68. }
  69. });
  70. return selected;
  71. }
  72. /**
  73. * 获取选中的行数组
  74. *
  75. * @returns {Array}
  76. */
  77. getSelectedRows() {
  78. let selected = [];
  79. $(this.options.checkboxSelector+':checked').each(function() {
  80. var id = $(this).data('id'), i, exist;
  81. for (i in selected) {
  82. if (selected[i].id === id) {
  83. exist = true
  84. }
  85. }
  86. exist || selected.push({'id': id, 'label': $(this).data('label')})
  87. });
  88. return selected;
  89. }
  90. }