繁体   English   中英

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

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

我正在写一个基于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中的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中的index查看templates中的分数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM