jQuery的表排序-更有效的方法?

时间:2018-11-17 23:19:22

标签: jquery ajax

我正在通过PHP AJAX填充表,并且正在使用JQuery对列进行排序。有没有更有效的编码方式? :

$(document).on('click', '.thPartNumber', function() {
        if (clicked == 1) {
            fetch_data('PartNumber ASC');
            clicked = clicked + 1;
        }
        else if (clicked == 2) {
            fetch_data('PartNumber DESC');
            clicked = 1;
        }
    });
    $(document).on('click', '.thPartName', function() {
        if (clicked == 1) {
            fetch_data('PartName ASC');
            clicked = clicked + 1;
        }
        else if (clicked == 2) {
            fetch_data('PartName DESC');
            clicked = 1;
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以

  • 将其组合为一个单击事件,并使用.hasClass()确定零件
  • 将(int)clicked更改为(boolean)clickFlag

var clickFlag = false;

$('.thPartNumber, .thPartName').on('click', function() {
  clickFlag = !clickFlag;
  var $this = $(this),
      order = clickFlag ? 'ASC' : 'DESC',
      name;
      
  if ($this.hasClass('thPartNumber')) {
    name = 'PartNumber';
  } else if ($this.hasClass('thPartName') {
    name = 'PartName';
  }
  
  fetch_data(name . ' ' . order);
});