简体   繁体   中英

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

I am writing a javascript based filter:

There a lots of divs with the class .single that contain multiple text elements. The filter already hides all .single 's that do not contain words:

//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. The array templates contains objects with all the text per .single and a score based on relevance and number of words. 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)

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).

If you add the score to elements as data() in your $.each

$(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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