2012-11-20 63 views
1

我正在使用tablesorter对表内容进行排序。我的表格如下。jQuery Table sorter排序浮点距离

<table class="results" border="1"> 
<thead> 
    <tr> 
     <th class="header">No</th> 
     <th class="header">Distance</th> 
     <th class="header">Diagnostic Fee</th> 
     <th class="header">Regular Price </th> 
     <th class="header">Company Price</th> 
     <th class="">&nbsp;</th> 
    </tr> 
</thead> 

<tbody> 
    <tr> 
     <td>1</td> 
     <td class="distance"><a>16.50 kms.</a></td> 
     <td class="brand"><a>Credited</a></td> 
     <td><a>$5</a></td> 
     <td><a>$5<small>after 5% cash back</small></a></td> 
    </tr> 
    <tr> 
      <td>2</td> 
     <td class="distance"><a>6.30 kms.</a></td> 
     <td class="brand"><a>Credited</a></td> 
     <td><a>$8</a></td> 
     <td><a>$8<small>after 5% cash back</small></a></td> 
    </tr> 
    <tr> 
     <td>3</td> 
     <td class="distance"><a>10.25 kms.</a></td> 
     <td class="brand"><a>Credited</a></td> 
     <td><a>$2</a></td> 
     <td><a>$2<small>after 5% cash back</small></a></td> 
    </tr> 
</tbody> 
</table>​ 

我想使用距离和价格对表格进行排序。 我面临的困难是解决与距离表,因为距离显示在像字母数字“12公里”。所以,表格没有被排序。

任何人都可以建议如何解析的内容通过只有数字?

这里是jsfiddle demo

回答

1

Tablesorte有一个选项“textExtraction”,这样你就可以定义一个函数在排序前要经过的文本。例如:

$("table").tablesorter({ 
     debug:false, 
     sortList: [[0, 0], [2, 0]], 
     textExtraction: function(node) { 
      var $node = $(node) 
      var text = $node.text(); 
      if ($node.hasClass('distance')) { 
       text = text.replace('kms', ''); 
      }; 

      return text; 
     } 
}); 

Updated fiddle

+0

对于许多不同的列会比较麻烦,最好使用解析器。 – EMMERICH

5

的tablesorter提供限定用于在其中它不能正确地获取数据单元附加解析器的一种方式。您需要定义2个解析器为2列你感兴趣

所以,你可能有:

$.tablesorter.addParser({ 
    id: 'distance', 
    is: function(s) { 
    return false; 
    }, 
    format: function(text, table, cell) { 
    return parseFloat(text.replace('kms.', '')); 
    }, 
    type: 'numeric' 
}); 

的距离,并且:

$.tablesorter.addParser({ 
    id: 'price', 
    is: function(s) { 
    return false; 
    }, 
    format: function(text, table, cell) { 
    return parseFloat(text.replace('$', '')); 
    }, 
    type: 'numeric' 
}); 

价格。然后你告诉tablesorter要使用哪些列解析,所以:

$("table").tablesorter({ 
    debug:false, 
    sortList: [[0, 0], [2, 0]], 
    headers: { 
    1: { 
     sorter: 'distance' 
    }, 
    3: { 
     sorter: 'price' 
    } 
    } 
});​ 
+0

谢谢你EMMERICH ..! –

+1

这很好。我猜你接受了错误的答案^^ – EMMERICH

+0

+1。我只做,因为,jsfiddle运作良好,代码少。操作系统应该允许接受多个答案:) –