简体   繁体   English

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

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

I am writing a javascript based filter: 我正在写一个基于JavaScript的过滤器:

There a lots of divs with the class .single that contain multiple text elements. 有很多.single类的div,其中包含多个文本元素。 The filter already hides all .single 's that do not contain words: 过滤器已经隐藏了所有不包含单词的.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);

The array included contains all indexes of .single 's that contain atleast one word. 包含的数组included .single的所有索引,其中至少包含一个单词。 The array templates contains objects with all the text per .single and a score based on relevance and number of words. 数组templates包含对象,每个对象带有.single文本,以及基于相关性和单词数的分数。 For example: 例如:

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

(So all indexing doesn't happen in the DOM) (因此所有索引都不会在DOM中发生)

Now what I want is to sort the set based on this score, or in other words: the highest score on the top. 现在,我想要的是根据该分数对集合进行排序,或者换句话说:最高分数。 The index of each element in the set is the same as the index in templates (which contains all scores). 集合中每个元素的索引与templates (包含所有分数)中的索引相同。

If you add the score to elements as data() in your $.each 如果将分数作为元素添加为$ .each中的data()

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

You could then use the scores to sort 然后,您可以使用分数进行排序

function scoreSort(a, b) {
    return $(a).data('score') > $(b).data('score') ?1 :-1;

}

singles.sort( scoreSort);

/* now replace html*/

container.append( singles);

I may be missing something, you say you want them in index order of templates but they must already be in that order for you to look at scores in templates using index in $.each 我可能遗漏了一些东西,您说要按templates索引顺序进行操作,但是它们必须已经按照该顺序排列,以便您可以使用$ .each中的index查看templates中的分数。

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

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