【问题标题】:Sorting using jQuery [duplicate]使用 jQuery 排序 [重复]
【发布时间】:2014-07-14 04:51:19
【问题描述】:

我有以下代码。 如何使用 jQuery 按 DESC 顺序对它们进行排序?或者是否可以使用 CSS 进行排序?但我更喜欢 jQuery...

<div class="bf-attr-block-cont">

<div class="bf-attr-filter bf-attr-2 bf-row">
    <span class="bf-cell bf-c-1">
        <input type="checkbox" value="2pm.com" name="attribute_value[2][]" id="bf-attr-2-0">
    </span>
    <span class="bf-cell bf-c-2">
        <label class="bf-attr-val" for="bf-attr-2-0">2pm.com</label>
    </span>
    <span class="bf-cell bf-c-3"><span class="bf-count">4</span></span>
</div>

<div class="bf-attr-filter bf-attr-2 bf-row">
    <span class="bf-cell bf-c-1">
        <input type="checkbox" value="Adidas" name="attribute_value[2][]" id="bf-attr-2-1">
    </span>
    <span class="bf-cell bf-c-2">
        <label class="bf-attr-val" for="bf-attr-2-1">Adidas</label>
    </span>
    <span class="bf-cell bf-c-3"><span class="bf-count">2</span></span>
</div>

<div class="bf-attr-filter bf-attr-2 bf-row">
    <span class="bf-cell bf-c-1">
        <input type="checkbox" value="AJ Morgan" name="attribute_value[2][]" id="bf-attr-2-2">
    </span>
    <span class="bf-cell bf-c-2">
        <label class="bf-attr-val" for="bf-attr-2-2">AJ Morgan</label>
    </span>
    <span class="bf-cell bf-c-3"><span class="bf-count">2</span></span>
</div>              

【问题讨论】:

  • 检查这个:link
  • 按什么排序?
  • 根据 bf-count 排序
  • @MajidAkbari,我需要按数字排序,而不是按字母排序
  • 使用parseInt(val, 10) 进行数字排序。就是这样。

标签: jquery


【解决方案1】:

如果你想在标签上按字母排序,你可以这样做:

$('.bf-attr-block-cont').append($('.bf-attr-block-cont .bf-attr-filter').sort(function(d1,d2){
   var s1 = $('label', d1).text().trim().toLowerCase(), 
       s2 = $('label', d2).text().trim().toLowerCase();
   if (s1===s2) return 0;
   return s1<s2 ? 1 : -1;
}));

Demonstration

如果您想根据 .bf-count 进行排序,请执行以下操作:

$('.bf-attr-block-cont').append($('.bf-attr-block-cont .bf-attr-filter').sort(function(d1,d2){
   var s1 = parseFloat($('.bf-count', d1).text().trim()), 
       s2 = parseFloat($('.bf-count', d2).text().trim());
   if (s1===s2) return 0;
   return s1<s2 ? 1 : -1;
}));

Demonstration

请注意,这些类型不会破坏事件处理程序绑定,这与更改 innerHTML 的幼稚解决方案相反。

【讨论】:

  • 演示看起来不错,让我把它们放在我的代码中,然后恢复
  • 我测试了我的代码,但它似乎与 .bf-attr-block-cont 的第一个 div 冲突。所以我尝试将新类“brands”添加到 .bf-attr-block-cont 的第二个 div 中,并在你的 js 代码中替换 bf-attr-block-cont,但它没有排序。
  • 你能用最小的小提琴重现你的问题吗?
  • 我把我网站上的代码复制到了你的 JS Bin 中,看起来运行良好。是因为我网站上的 js 冲突吗?
  • @redcoder 没有更多信息很难说。我建议你debug to see what happens
猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 2016-07-31
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多