2011-07-18 85 views
8

我想根据其类名重新排列表行。
以下是我的HTML代码。根据类名对表格行排序

<table> 
<tr class="a4"><td>4</td></tr> 
<tr class="a6"><td>6</td></tr> 
<tr class="a1"><td>1</td></tr> 
<tr class="a2"><td>2</td></tr> 
<tr class="a5"><td>5</td></tr> 
<tr class="a3"><td>3</td></tr> 
</table> 

所以,现在,与类名A1应该首先显示,同样A2第二。等等。

请人帮我

回答

12

我如果您不想依赖外部插件,则可以使用match()从类名称中提取数字,并使用内置的sort()方法对元素进行排序。

从那里,你可以使用append()重新排序表中的行(它会删除表的每一行,然后在适当的位置重新添加):

$("table").append($("tr").get().sort(function(a, b) { 
    return parseInt($(a).attr("class").match(/\d+/), 10) 
     - parseInt($(b).attr("class").match(/\d+/), 10); 
})); 

你可以看到在this fiddle结果。

+0

令人惊异的想法..非常感谢:-) – Reddy

+0

谢谢你的好主意。 – zero8

3

你可以使用this插件和喜欢的东西:

jQuery.fn.sortElements = (function(){ 

    var sort = [].sort; 

    return function(comparator, getSortable) { 

     getSortable = getSortable || function(){return this;}; 

     var placements = this.map(function(){ 

      var sortElement = getSortable.call(this), 
       parentNode = sortElement.parentNode, 

       // Since the element itself will change position, we have 
       // to have some way of storing its original position in 
       // the DOM. The easiest way is to have a 'flag' node: 
       nextSibling = parentNode.insertBefore(
        document.createTextNode(''), 
        sortElement.nextSibling 
       ); 

      return function() { 

       if (parentNode === this) { 
        throw new Error(
         "You can't sort elements if any one is a descendant of another." 
        ); 
       } 

       // Insert before flag: 
       parentNode.insertBefore(this, nextSibling); 
       // Remove flag: 
       parentNode.removeChild(nextSibling); 

      }; 

     }); 

     return sort.call(this, comparator).each(function(i){ 
      placements[i].call(getSortable.call(this)); 
     }); 

    }; 

})(); 
// do the sorting 
$('tr').sortElements(function(a, b){ 
    return $(a).attr('class') > $(b).attr('class') ? 1 : -1; 
}); 

小提琴这里:http://jsfiddle.net/ZV5yc/1/

+0

我认为这是更好的有更高的评价谢谢。 – zero8

+0

http://jsfiddle.net/zeroeight/ZV5yc/50/ – zero8

相关问题