简体   繁体   中英

How can I sort img elements according to an attribute?

I have a list of img elements in a div, like this :

<img src="..." pct="38"/>

The value of pct is different for every image. I've managed to create a list containing all my images, with an each() loop.

var tab[];

But I have no idea of how to sort it easily, and if there is a quick way. What should I do ?

If you define a sortByPct function like this where a and b are DOM elements:

var sortByPct = function(a, b) {
  var aNum = new Number($(a).attr("pct"));
  var bNum = new Number($(b).attr("pct"));
  return aNum == bNum ? 0 : (aNum < bNum ? -1 : 1);
}

... you will be able to sort your array the following way:

tab.sort(sortByPct);

You can use the sort function and pass it a dedicated comparison function :

var strcmp = function(str1, str2) {
    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
};
// to sort by src :
tab.sort(function(a,b) {
    return strcmp(a.attr('src'), b.attr('src'));
});
// to sort by "pct" :
tab.sort(function(a,b) {
    return strcmp(a.attr('pct'), b.attr('pct'));
});
// to sort by "pct" as numbers :
tab.sort(function(a,b) {
    return a.attr('pct') - b.attr('pct');
});

This assumes your tab array contains jQuery objects. If that's not the case, use $(a).attr('pct') instead of a.attr('pct') .

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