[removed] Ordinal suffix for numbers with specific CSS class

前端 未结 8 1360
时光说笑
时光说笑 2021-02-14 03:01

I am trying to display numbers within a particular table with ordinal suffixes. The table always shows three numbers which come from an XML file. The numbers show ranks, so for

8条回答
  •  抹茶落季
    2021-02-14 03:14

    I would do something like this, based on David Thomas's answer:

    Number.prototype.ordinate = function(){
        var num = this,
            ones = num % 10, //gets the last digit
            tens = num % 100, //gets the last two digits
            ord = ["st","nd","rd"][ tens > 10 && tens < 20 ? null : ones-1 ] || 'th';
        return num.toString() + ord;
    };
    

    It accomplishes the same thing. If a number's last 2 digits are within the 11-19 range OR the last digit is between 4-0 it defaults to 'th', otherwise it will pull a 'st', 'nd' or 'rd' out of the array based on the ones place.

    I like the idea of creating a prototype function very much but I would definitely leave the incrementation of the index outside of the prototype function to make it more versatile:

    $(".ordinal").text(function (i, t) {
        return (++i).ordinate();
    });
    

    JS Fiddle Demo

提交回复
热议问题