如何更改匹配的jQuery集合中元素的顺序

How to change the order of elements in a matched jQuery set

本文关键字:元素 顺序 集合 jQuery 何更改      更新时间:2023-09-26

我正在编写一个基于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中的索引相同(包含所有分数)。

如果将分数作为数据()添加到$.each 中的元素

$(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的索引顺序排列,但它们必须已经按该顺序排列,你才能使用$.中的索引查看templates中的分数。每个