开发者

jquery Doing Simple Math?

I have a little DIV like this:

<div id=开发者_JAVA百科"counter">2</div>

I'd like to use jQUery to either subtract or add by let say 1, resulting in 3 or 1...

is there a way in jquery to do this? convert a string to a int maybe?


$('#counter').text(function(i, txt) {
    return +txt + 1;
});

That way, the content from #counter are converted into an integer. This works great for numbers, but if for some reason something like "foo123" is the content, it would become NaN.

So another way to parse it is to use .parseInt()

$('#counter').text(function(i, txt) {
    return parseInt(txt, 10) + 1;
});

parseInt() expects two arguments, a value and a radix (base number). If this is invoked on "foo123" it will return "123". One could say that this is a wrong behavior, so you need to decide which variant you want to have.

Example: http://www.jsfiddle.net/Mtvju/

Ref.: .text()


$('#counter').text(function(i,txt) { return parseInt(txt, 10) + 1; });

Example for addition: http://jsfiddle.net/2uBMy/

Example for subtraction: http://jsfiddle.net/2uBMy/1/

To add a check for negative, you could do this:

$('#counter').text(function(i,txt) {
    var result = parseInt(txt, 10) - 1;
    return (result > 0) ? result : 0; 
});


var counter = $('#counter');
var value   = parseInt(counter.html());
counter.html(value + 1);


$('#counter').html(  +($('#counter').html()) + 1 );


Yes, convert it to an int. Use parseInt to convert it to an integer. Then use jQuery's .html to get the contents of the <div> and to replace those contents with the new value.

$("#counter").html(parseInt($("#counter").html(),10) + 1)
$("#counter").html(parseInt($("#counter").html(),10) - 1)

Try it here!


javascript is loosely typed. You can use strings that contain numbers and numbers as if they where both for most purposes. The one place to be careful is the +, which is both add and concatenate. You need to disambiguate somehow.

function subtract()
{
   count = $('#counter').html();
   if(count > 0)
   {
     count--;
   }
   $('#counter').html(count)
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜