jQuery & lt; tag>按不同选项排序

jQuery <tag> sorting by different options

本文关键字:选项 排序 lt tag jQuery      更新时间:2023-09-26

例如:

<a href='#' id='by_id'>Sort by id</a>
<a href='#' id='by_author'>Sort by author</a>
<a href='#' id='by_title'>Sort by title</a>
<div id="my_list">
  <div data-id='1' data-author='Pushkin'>Fairy Tale</div>
  <div data-id='3' data-author='Tolstoy'>Anna Karenina</div>
  <div data-id='2' data-author='Doyl'>Fairy Tale</div>
  <div data-id='5' data-author='Tarantino'>Kill Bill</div>
  <div data-id='9' data-author='Pushkin'>Fairy Tale</div> 
</div>

现在我想通过点击我的酷链接按标题,id或作者对我的div进行排序。

是否有一个插件为这项工作或很容易实现没有任何外部库?

轻巧,简单。试试这个:)

$('#sortables').delegate('a', 'click', function() {
    var by = $(this).attr('id').match(/^by_(.*)/i);
    if (by)
    {
      mySort.sort(by[1]);
    }
});
var mySort = {
  sortables: {
    'title': {
      method: 'text',
      type: 'alpha'
    },
    'author': {
      method: 'attr',
      val: 'data-author',
      type: 'alpha'
    },
    'id': {
      method: 'attr',
      val: 'data-id',
      type: 'numeric'
    }
  },
  sort: function(sortBy)
  {
    if (!mySort.sortables[sortBy]) return;
    var sortedElements = [];
    var sortVal;
    var sort = mySort.sortables[sortBy];
    $('#my_list > div').each(function() {
      sortVal = $(this)[sort.method](sort.val || null);
      sortedElements.push([this, sortVal]);
    });
    // ">" sorts in ascending order, "<" will sort in descending order.
    sortedElements.sort(function(a, b) {
        var result;
        return (sort.type == 'numeric') ?
            a[1] - b[1] :
            a[1] > b[1];
    });
    // Create a new div to replace the old one with
    var $newDiv = $('<div id="my_list">');
    $(sortedElements).each(function() {
        $newDiv.append(this[0]);
    });
    $('#my_list').replaceWith($newDiv);
  }
};

Working fiddle here: http://jsfiddle.net/fHTmQ/3

我认为你可以使用datagrid插件,

http://www.trirand.com/blog/?page_id=5