【问题标题】:Sort li by data-id of child element - jQuery按子元素的数据ID排序li - jQuery
【发布时间】:2012-06-27 01:07:15
【问题描述】:

所以我试图通过每个<li> 中的子元素的 data-id 属性对无序列表进行排序。如何定位此元素以按其值排序?

这是我当前的代码:

    $("#sort_popularity").live("click", function() {
        var listitems = list.children('li').get();

        listitems.sort(function(a, b) {
            var compA = $(a).("#subject_popularity");
            var compB = $(b).("#subject_popularity");
            return compA < compB;
        });

        $.each(listitems, function(index, item) {
            list.append(item); // (List is defined elsewhere in my code)
        });
    });

HTML:

<a href="#" id="sort_popularity">Sort</a>

<ul>
    <li><span id="popularity" data-id="10">10</li>
    <li><span id="popularity" data-id="20">20</li>
    <li><span id="popularity" data-id="5">5</li>
</ul>

【问题讨论】:

标签: javascript jquery html


【解决方案1】:
// for ASC.
var lis = $('ul li');

lis.sort(function(a, b) {
    return parseInt($('span', a).data('id'), 10) > parseInt( $('span', b).data('id'), 10);
});

$('ul').html(lis);

// for DESC.
var lis = $('ul li');

lis.sort(function(a, b) {
    return parseInt( $('span', a).data('id'), 10) < parseInt( $('span', b).data('id'), 10);
});

$('ul').html(lis);

注意

ids 的spans 更改为多个spanid 并关闭您的span 标签(可能是拼写错误)。

【讨论】:

  • 我将 id 属性更改为“name”。它在 FireFox 中运行良好,但在 Safari 中却不行。知道为什么会这样吗?
  • @Sneaksta 而不是name 将它们更改为class,我认为name 不是span 的首选,并保持data-id 不变
  • @Sneaksta 你能把你试过的东西调一下,然后在这里分享
  • 跨度格式不正确。试试&lt;li&gt;&lt;span class="popularity" data-id="10"&gt;10&lt;/span&gt;&lt;/li&gt; ...,或&lt;li class="popularity" data-id="10"&gt;10&lt;/li&gt; ...。
猜你喜欢
  • 2015-04-01
  • 2021-10-10
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
相关资源
最近更新 更多