RowSelector.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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._bind()
  17. }
  18. _bind() {
  19. let options = this.options,
  20. checkboxSelector = options.checkboxSelector,
  21. $selectAllSelector = $(options.selectAllSelector),
  22. $checkbox = $(checkboxSelector);
  23. $selectAllSelector.on('change', function() {
  24. var cbx = $(this).parents(options.container).find(checkboxSelector);
  25. for (var i = 0; i < cbx.length; i++) {
  26. if (this.checked && !cbx[i].checked) {
  27. cbx[i].click();
  28. } else if (!this.checked && cbx[i].checked) {
  29. cbx[i].click();
  30. }
  31. }
  32. });
  33. if (options.clickRow) {
  34. $checkbox.click(function (e) {
  35. if (typeof e.cancelBubble != "undefined") {
  36. e.cancelBubble = true;
  37. }
  38. if (typeof e.stopPropagation != "undefined") {
  39. e.stopPropagation();
  40. }
  41. }).parents('tr').click(function (e) {
  42. $(this).find(checkboxSelector).click();
  43. });
  44. }
  45. $checkbox.on('change', function () {
  46. var tr = $(this).closest('tr');
  47. if (this.checked) {
  48. tr.css('background-color', options.background);
  49. if ($(checkboxSelector + ':checked').length === $checkbox.length) {
  50. $selectAllSelector.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. }