【问题标题】:Sorting table rows based on column class names using jquery使用jquery根据列类名对表行进行排序
【发布时间】:2016-11-16 02:13:12
【问题描述】:

与这个问题非常相似:Sort table rows based on their Class Names
考虑下表:

<table>
   <thead>
       <th>A column</th>
   </thead>
   <tbody>
       <tr>
           <td class="x">A</td>
       </tr>
       <tr>
           <td class="c">B</td>
       </tr>
       <tr>
           <td class="">C</td>
       </tr>
   </tbody>
</table>

我想根据第一个(仅在这种情况下)列类名称对行进行排序。一些td 没有指定类。所以想要的效果是:A-B-C -&gt; C-B-A or B-A-C(我不在乎无类 tds 放在哪里)。我知道我可以用 jquery 上课,例如:

$(table tr).eq(1).find('td').eq(0).attr('class')

有什么想法吗?

【问题讨论】:

  • 请提供尝试过的解决方案,为什么它们不起作用,以及预期的结果。这确实有助于我们找出您的代码的问题。谢谢!

标签: javascript jquery html sorting html-table


【解决方案1】:

使用sort()tr 元素的数组进行排序。您可以通过排序和设置每个元素的排列功能来获取元素的类。

$("table tbody tr").sort(function (a, b){
    return $("td", b).attr("class") < $("td", a).attr("class") ? 1 : -1;    
}).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
        <th>A column</th>
    </thead>
    <tbody>
        <tr>
            <td class="x">A</td>
        </tr>
        <tr>
            <td class="c">B</td>
        </tr>
        <tr>
            <td class="">C</td>
        </tr>
    </tbody>
</table>

【讨论】:

  • 这类作品。它会产生一些新行,这是因为每一行在其中一列中都有一个模块吗?如果我在你的函数之前和之后调用 $('table').size() ,我会得到两个不同的结果。
  • @peech 我看不出有什么不同。见jsfiddle.net/bybgt827
  • 嗯。我认为问题在于我在前面谈到的模块中有一个日期选择器。没关系,我自己研究一下。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2016-11-13
  • 2013-01-19
  • 1970-01-01
相关资源
最近更新 更多