0

在 Forumotion 上使用 PunBB 的想法是使用 Points 系统将显示的点数替换为一串文本。使用 span 类,我首先在代码周围定义了一个类“honorpoints”,显示用户拥有的点数。

<span class="honorpoints"><!-- BEGIN profile_field -->{postrow.displayed.profile_field.CONTENT}<!-- END profile_field --></span>

在论坛上使用该代码时,它将根据用户的积分在用户名旁边显示一个数字。以下 jQuery 代码是我试图用来替换数字的代码。

$(".honorpoints").each(function(){
    var elm = $(this);
    var number = parseFloat(elm.text(), 10);
    if (number >= 1 && number <= 500) {
        state = "rank 1";
    } else if (number >= 500 && number < 3000) {
        state = "rank 2";
    }
    elm.text(state);
});

但是,这没有任何作用,并且数字仍然存在。它应该将 UserA : 234 和 UserB : 571 替换为 UserA : rank 1 和 UserB : rank 2 。但是,当在 jsFiddle 上使用并且仅使用数字而不是 {postrow.displayed.profile_field.CONTENT} 代码时,该代码确实有效. 帮助表示赞赏!

4

2 回答 2

0

查看您在评论中提供的页面的来源,我相信您的$('.honorpoints').each方法在文档完全加载之前被调用(99546.js)。除非我遗漏了什么,否则您需要将该方法包装在一个$(document).ready函数中,以便仅在 DOM 准备好后才执行它:

$(document).ready(function() {
    $(".honorpoints").each(function(){
        var elm = $(this);
        var number = parseFloat(elm.text(), 10);
        var state = "";
        if (number >= 1 && number <= 500) {
            state = "rank 1";
        } else if (number >= 500 && number < 3000) {
            state = "rank 2";
        }
        elm.text(state);
    });
});

我还为变量添加了一个声明,state因为这是一个很好的做法(因为它目前在您的问题中,该state变量实际上是window.state因为它之前没有声明过)。

于 2012-08-01T00:40:30.840 回答
0

以下行尝试解析"UserA : 234",这就是您收到错误的原因。parseFloat(elm.text(), 10);

你必须修复你if的 s,两者都匹配500

您可以使用以下代码修复它:

$(".honorpoints").each(function(){
    $(this).text(function(i, text) {
        return text.replace(/\d+$/, function(match) {
            if(match >= 1 && match <= 500) return "rank 1";
            else if(match > 500 && match < 3000) return "rank 2";
        });
    });
});

解释:

$: 匹配字符串结尾;
\d: 只匹配数字;
+: 匹配匹配一次或多次,所以可以匹配0and 5000000;

演示

参考资料

于 2012-08-01T00:15:46.750 回答