【问题标题】:How to change the order of elements in a matched jQuery set如何更改匹配的 jQuery 集中元素的顺序
【发布时间】:2012-03-19 02:02:33
【问题描述】:

我正在编写一个基于 javascript 的过滤器:

有很多类 .single 的 div 包含多个文本元素。过滤器已经隐藏了所有不包含单词的.single

//take them off dom, manip and put them back
singles.detach().each(function(i) {
    var $this = $(this);

    //make sure everything is visible
    $this.show();

    //if this template is not included OR if this index number does not meet the treshold
    if($.inArray(i, included) == -1 || treshold >= templates[i].score) {
        $this.hide();
    }
}).appendTo(container);

数组included 包含.single 的所有索引,其中至少包含一个单词。数组templates 包含具有每个.single 的所有文本的对象以及基于相关性和字数的分数。例如:

templates = [
    { text: ['long string', 'long string 2'], score: 5 },
    { text: ['sf sd', 'gdasd'], score: 3 }
]

(因此所有索引都不会发生在 DOM 中)

现在我想要的是根据这个分数对集合进行排序,或者换句话说:最高分在顶部。集合中每个元素的索引与templates 中的索引相同(包含所有分数)。

【问题讨论】:

    标签: javascript jquery sorting filter set


    【解决方案1】:

    如果您在 $.each 中将分数作为 data() 添加到元素中

    $(this).data('score', templates[i].score);
    

    然后您可以使用分数进行排序

    function scoreSort(a, b) {
        return $(a).data('score') > $(b).data('score') ?1 :-1;
    
    }
    
    singles.sort( scoreSort);
    
    /* now replace html*/
    
    container.append( singles);
    

    我可能遗漏了一些东西,您说您希望它们按templates 的索引顺序排列,但它们必须已经按照该顺序排列,您才能使用 $.each 中的索引查看 templates 中的分数

    【讨论】:

    • 我使用的是 $(elem).each() 而不是 $.each()。模板和集合的顺序已经相同,所以我可以使用data 绑定分数(感谢提示)。但是,您建议的排序不是按分数排序,而是显示不同的结果(我不明白为什么)。
    • 你是对的,它有效。那一定是我的其他代码。感谢您的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多