rf2*_*012 11 javascript jquery ordinals
我试图在带有序数后缀的特定表格中显示数字.该表始终显示来自XML文件的三个数字.数字显示排名,例如他们可能是第6,120,131.输出是一个如下所示的表:
<table>
<tr>
<td class='ordinal'>6</td>
<td class='ordinal'>120</td>
<td class='ordinal'>131</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
理想情况下我想使用javascript,我在stackoverflow上找到了一些非常好的解决方案,例如这个.但是,我正在努力将该函数应用于表中的所有数字,而不是单独输入每个数字.我尝试使用CSS类,以便我的函数看起来像这样:
<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>
Run Code Online (Sandbox Code Playgroud)
但它不起作用,可能是因为我把代码搞砸了.也许这里有人可以帮助我,告诉我哪里出错了?
非常感谢您的帮助!
Dav*_*mas 12
我自己的建议是:
$(".ordinal").text(function (i, t) {
i++;
var str = i.toString().slice(-1),
ord = '';
switch (str) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
ord = 'th';
break;
}
return i + ord;
});
Run Code Online (Sandbox Code Playgroud)
这有效地采用递增的数字(i++为了1从不开始0),将其转换为字符串,然后查看该字符串的最后一个数字.这应该适用于任何数量,因为序纯粹是基于对最后一个号码.
您还可以扩展Number原型以实现此功能:
Number.prototype.ordinate = function(){
var num = this + 1,
last = num.toString().slice(-1),
ord = '';
switch (last) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
ord = 'th';
break;
}
return num.toString() + ord;
};
$(".ordinal").text(function (i, t) {
return i.ordinate();
});
Run Code Online (Sandbox Code Playgroud)
编辑提供一个轻微的选择:
Number.prototype.ordinate = function(){
var num = this,
last = num.toString().slice(-1),
ord = '';
switch (last) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
default:
ord = 'th';
break;
}
return num.toString() + ord;
};
$(".ordinal").text(function (i,t) {
return t.replace(/(\d+)/g, function(a){
return parseInt(a, 10).ordinate();
});
});
Run Code Online (Sandbox Code Playgroud)
这基本上遍历每个.ordinal元素,用添加了序数后缀的(相同)数字替换存在的数字.
编辑,以解决该问题,在评论,下面提出的,即11,12和13正在接受的序后缀st,nd和rd(分别).现在,这已th在所有情况下得到纠正:
Number.prototype.ordinate = function(){
var num = this,
numStr = num.toString(),
last = numStr.slice(-1),
len = numStr.length,
ord = '';
switch (last) {
case '1':
ord = numStr.slice(-2) === '11' ? 'th' : 'st';
break;
case '2':
ord = numStr.slice(-2) === '12' ? 'th' : 'nd';
break;
case '3':
ord = numStr.slice(-2) === '13' ? 'th' : 'rd';
break;
default:
ord = 'th';
break;
}
return num.toString() + ord;
};
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
4960 次 |
| 最近记录: |