RowSelector.js 2.9 KB

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