RowSelector.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. $(this).parents(options.container).find(checkboxSelector).prop('checked', this.checked).trigger('change');
  25. });
  26. if (options.clickRow) {
  27. $document.off('click', checkboxSelector).on('click', checkboxSelector, function (e) {
  28. if (typeof e.cancelBubble != "undefined") {
  29. e.cancelBubble = true;
  30. }
  31. if (typeof e.stopPropagation != "undefined") {
  32. e.stopPropagation();
  33. }
  34. });
  35. $document.off('click', options.container+' tr').on('click', options.container+' tr', function () {
  36. $(this).find(checkboxSelector).click();
  37. });
  38. }
  39. $document.off('change', checkboxSelector).on('change', checkboxSelector, function () {
  40. var tr = $(this).closest('tr');
  41. if (this.checked) {
  42. tr.css('background-color', options.background);
  43. if ($(checkboxSelector + ':checked').length === $(checkboxSelector).length) {
  44. $(selectAll).prop('checked', true)
  45. }
  46. } else {
  47. tr.css('background-color', '');
  48. }
  49. });
  50. }
  51. /**
  52. * 获取选中的主键数组
  53. *
  54. * @returns {Array}
  55. */
  56. getSelectedKeys() {
  57. let selected = [];
  58. $(this.options.checkboxSelector+':checked').each(function() {
  59. var id = $(this).data('id');
  60. if (selected.indexOf(id) === -1) {
  61. selected.push(id);
  62. }
  63. });
  64. return selected;
  65. }
  66. /**
  67. * 获取选中的行数组
  68. *
  69. * @returns {Array}
  70. */
  71. getSelectedRows() {
  72. let selected = [];
  73. $(this.options.checkboxSelector+':checked').each(function() {
  74. var id = $(this).data('id'), i, exist;
  75. for (i in selected) {
  76. if (selected[i].id === id) {
  77. exist = true
  78. }
  79. }
  80. exist || selected.push({'id': id, 'label': $(this).data('label')})
  81. });
  82. return selected;
  83. }
  84. }