我正在尝试使用 html 元素包装函数的返回值

I am trying to wrap a return value from a function with an html element

本文关键字:包装 元素 函数 返回值 html      更新时间:2023-09-26

嗨,我正在使用后缀函数将 th、st 和 rd 添加到数字中,但我试图用跨度包装实际的后缀,不知何故它不起作用,不知道为什么。

感谢您的帮助,它可以将其切换到html,是否有机会删除计数器本身,因为我正在从DB中获取所有数字,只需要在数字中添加后缀,而不是两者兼而有之。我从div 中删除了数字,但仍然得到数字。

这是代码

<div></div>
<div></div>
<div></div>
<div></div>
$("div").html(function (i, t) {
        i++;
        var str = i.toString().slice(-1),
            suffix = '';
        switch (str) {
            case '1':
                suffix = i.toString().slice(-2) === '11' ? 'th': 'st';
                break;
            case '2':
                suffix = i.toString().slice(-2) === '12' ? 'th' : 'nd';
                break;
            case '3':
                suffix = i.toString().slice(-2) === '13' ? 'th' : 'rd';
                break;
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                suffix = 'th';
                break;
        }
         return i + '<span>' + suffix + '</span>';
    });

如果将 .text() 更改为 .html() 是否有效?

<div>1</div>
<div>2</div>    
<div>3</div>
<div>4</div>
$("div").html(function (i, t) {
    i++;
    var str = i.toString().slice(-1),
        suffix = '';
    switch (str) {
        case '1':
            suffix = i.toString().slice(-2) === '11' ? 'th': 'st';
            break;
        case '2':
            suffix = i.toString().slice(-2) === '12' ? 'th' : 'nd';
            break;
        case '3':
            suffix = i.toString().slice(-2) === '13' ? 'th' : 'rd';
            break;
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
        case '0':
            suffix = 'th';
            break;
    }
     return i + '<span>' + suffix + '</span>';
});

示例:http://jsfiddle.net/2d02k5ou/