2011-07-18 83 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

相關問題