RowSelector.js 2.7 KB

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