按数字对表格进行排序,并附有文字?

时间:2016-01-18 00:27:57

标签: jquery sorting tablesorter

我看到的所有示例都是用于排序只有数字的列的表。

但我想对这种表的价格列进行排序:

 <div id="main-table">
   <div class="wrap">
    <div class="table-wrapper tablesorter">
      <table border="1" class="fixed">
        <col style="width:100px;" />
        <col style="width:100px;" />
        <col style="width:100px;" />
        <col style="width:100px;" />
        <col style="width:100px;" />
        <col style="width:100px;" />
        <thead>
          <tr>
            <th>h1</th>
            <th>h2</th>
            <th>h3</th>
            <th>Price</th>
            <th>h5</th>
            <th>h6</th>
          </tr>
        </thead>
        <tbody>
           <tr>
            <td>a</td>
            <td>700</td>
            <td>c</td>
            <td><span class="price">$75</span></td>
            <td>d</td>
            <td>e</td>
          </tr>
          <tr>
            <td>a</td>
            <td>20</td>
            <td>c</td>
            <td>Starting From <span class="price">$100</span></td>
            <td>d</td>
            <td>e</td>
          </tr>
          <tr>
            <td>a</td>
            <td>30</td>
            <td>c</td>
            <td>Today Only <span class="price">$50</span></td>
            <td>d</td>
            <td>e</td>
          </tr>
        </tbody>
      </table>
   </div>
 </div>  
</div>

它可能有类似&#34的字符串;从&#34;,&#34;今天只有&#34;等等。只有模式是我想要排序的值总是有$个标志在它旁边。

如果没有简单的方法可以做到这一点,那么我不介意一个解决方案,需要清洁的价格值出现在其他地方,例如<tr title="75">或其他任何地方,然后按title内的值对表进行排序。

我查了一下tablesorter插件,并没有真正理解文档。我猜这可能是某种文本提取功能,但我不知道如何为这种情况构建一个。

Here's a fiddle with my table and the plugin.

(现在我按b列排序,以确保插件真正有效)

另外,如何摆脱让观众按照他想要的标题对表格进行排序的选项?我只需要在加载页面时默认进行排序,这就是它。不想让观众修改排序,但在文档中没有找到如何摆脱标题内显示的那些箭头。

1 个答案:

答案 0 :(得分:1)

您可以添加自己的自定义解析器。在致电tablesorter之前添加此

$.tablesorter.addParser({ 
    // set a unique id 
    id: 'money', 
    is: function(s) { 
        // return false so this parser is not auto detected 
        return false; 
    }, 
    format: function(s) { 
      var matches = /\$(\d+)/.exec(s);
      return parseInt(matches ? matches[1] : 0);
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
}); 

然后在tablesorter选项中更新headers参数,以便它使用第3列的money分拣机,如:

 headers: {
    // set "sorter : false" (no quotes) to disable the column
    0: { sorter: false },
    1: { sorter: false },
    2: { sorter: false },
    3: {
        sorter: "money"  // for column 3 use the custom 'money' parser
    },
    4: { sorter: false },
    5: { sorter: false }

},

这将使用您的自定义分拣机。我在那里构建了正则表达式以查找$ ####的第一个条目(美元符号后跟数字)。如果数字的格式更复杂,您可以调整正则表达式。

相关问题