[removed] Ordinal suffix for numbers with specific

2019-04-05 12:08发布

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 example they may be 6th, 120th, 131st. The output is a table that would look like this:

<table>
    <tr>
        <td class='ordinal'>6</td>
        <td class='ordinal'>120</td>
        <td class='ordinal'>131</td>
    </tr>
</table>

I would ideally like to use javascript and I found a few very good solutions on stackoverflow, for example this one. However, I am struggling to apply the function to all numbers within the table, rather than putting in each number individually. I tried using a CSS class so that my function looks like this:

<script type="text/javascript">
$(function(){
    $(".ordinal").each(function(){
        var j = i % 10;
        if (j == 1 && i != 11) {
            return i + "st";
        }
        if (j == 2 && i != 12) {
            return i + "nd";
        }
        if (j == 3 && i != 13) {
            return i + "rd";
        }
        return i + "th";
        });
})
</script>

but it's not working, probably because I screwed up the code somewhere. Maybe somebody here can help me out and tell me where I went wrong?

Thank you very much for your help!

8条回答
成全新的幸福
2楼-- · 2019-04-05 12:43

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

查看更多
混吃等死
3楼-- · 2019-04-05 12:49

I created two approaches one using Prototype, the other as a plugin :

Number.prototype.between = function(n,m){ return this > n && this < m }
Number.prototype.ORDINATE_INDEX = ["th","st","nd","rd"];
Number.prototype.toOrdinate = function(){
    var
        nthMod = (this % 10),
        index =  nthMod > 3 || this.between(10,20) ? 0 : nthMod
    ;

    return this + this.ORDINATE_INDEX[index];
};

$(".ordinal").text(function (index, element) {
    return parseInt(element).toOrdinate();
});

This is the one as a Jquery Plugin :

(function($){
    var numberTool = new (function(){
        var private = {};

        private.ORDINATE_INDEX = ["th","st","nd","rd"];

        private.parseOrdinary = function(number)
        {
            var
                nthMod = (number % 10),
                index =  nthMod > 3 || private.between(number, 10,20) ? 0 : nthMod
            ;

            return number + private.ORDINATE_INDEX[index];
        }

        private.between = function(number, n,m){
            return number > n && number < m
        }

        this.isNumeric = function(number)
        {
            return !isNaN(parseFloat(number)) && isFinite(number);
        }

        this.toOrdinary = function(number)
        {
            return this.isNumeric(number) ? private.parseOrdinary(number) : number;
        }
    });


    $.fn.toOrdinary = function(){
        return this.each(function(){
            $element = $(this);
            $element.text(numberTool.toOrdinary($element.text()));
        }); 
    };
})(jQuery);

$(".ordinal").toOrdinary();
$(".ordinal").toOrdinary();
$(".ordinal").toOrdinary();

Tested on JSFIDDLE:

The prototype version example : http://jsfiddle.net/f8vQr/6/

The JQuery version example : http://jsfiddle.net/wCdKX/27/

查看更多
Lonely孤独者°
4楼-- · 2019-04-05 12:49

function ordsfx(a){return["th","st","nd","rd"][(a=~~(a<0?-a:a)%100)>10&&a<14||(a%=10)>3?0:a]}

See annotated version at https://gist.github.com/furf/986113#file-annotated-js

Short, sweet, and efficient, just like utility functions should be. Works with any signed/unsigned integer/float. (Even though I can't imagine a need to ordinalize floats)

查看更多
闹够了就滚
5楼-- · 2019-04-05 12:50

Ordinal suffix in one line

var integerWithSuffix=originalInteger+(['st','nd','rd'][( originalInteger +'').match(/1?\d\b/)-1]||'th');

the concatenation of the original number and a string representing the ordinal derived from an array indexed by the result of a regex search on that number

http://jsfiddle.net/thisishardcoded/DbSMB/

查看更多
Summer. ? 凉城
6楼-- · 2019-04-05 12:55

This is what I use, and it works for any year, month, day (leap year) included:

// panelyear, panelmonth and panelday are passed as parameters

var PY01 = parseInt(panelyear); var PM01 = (parseInt(panelmonth) - 1); PD01 = parseInt(panelday);

var now = new Date(PY01, PM01, PD01);
var start = new Date(PY01, 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);

function getNumberWithOrdinal(n) { var s = ["th","st","nd","rd"], v = n % 100; return n + (s[(v - 20) % 10] || s[v] || s[0]); }

Use with

<script> document.write(getNumberWithOrdinal(day)); </script>
查看更多
女痞
7楼-- · 2019-04-05 12:57
function nth(n){
    if(isNaN(n) || n%1) return n;   
    var s= n%100;
    if(s>3 && s<21) return n+'th';
    switch(s%10){
        case 1: return n+'st';
        case 2: return n+'nd';
        case 3: return n+'rd';
        default: return n+'th';
    }
}

You can take care of the teens in their own line, other integers follow the last digit rules.

查看更多
登录 后发表回答