开发者

replace number with string using jquery replacement

My question is related to this topic here.

I would need a jque开发者_JAVA百科ry replacement function for a number with a string as well, but much finer though.

My php returns a number in this format eg 1.27

Depending on a range this number should be replaced by a certain string that matches a range:

Example:

The number 1.27 is in the "active" range of 1.0 and 1.5, so the replacement for this would be the string "active". The value of 1.51 would be in the "less active" range from 1.5 to 2.0 and the replacement string would be the "less active" string.

Any ideas are much appreciated


Accessing the text in the page can be done using jQuery, but the rest of the code is plain Javascript.

You can use a regular expression to find the number, then use a function that determines what to replace it with, something like this:

var element = $('#id');
element.text(element.text().replace(/[\d\.]+/g, function(s){
  var n = parseDouble(s);
  if (n >= 1.0) {
    if (n <= 1.5) return "active";
    if (n <= 2.0) return "less active";
  }
  return s;
}));


Unfortunately you cannot do this with a single line of code. You'd have to do something like the following:

$(".number").each(function(){
    var elm = $(this);
    var number = parseFloat(elm.text(), 10);
    if (number >= 1 && number <= 1.5) {
        state = "active";
    } else if (number >= 1.5 && number < 2) {
        state = "less active";
    }
    elm.text(state);
});

See the above example on jsFiddle


I dont understand what jQuery has to do with it, but this is pretty simple really...

var state = 'Default';
if(value > 1 && value < 1.5)
 state = 'Active';
else if(value < 2)  
 state = 'Less active';
else if(value < 3)
 state = 'Sleeping';

You might want to get a good book about programming, this really shouldnt be an issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜