如何使用 javascript (jquery)将整数值添加到返回字符串的值中?

我有一个简单的 html 代码块,比如:

<span id="replies">8</span>

使用 jquery,我尝试将1添加到值(8)中。

var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);

现在的情况是:

81

那么

811

不是9,这是正确答案。我做错了什么?

268150 次浏览

parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.

var currentValue = parseInt($("#replies").text(),10);

The second paramter (radix) makes sure it is parsed as a decimal number.

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1

to increment by one you can do something like

  var newValue = currentValue ++;

In regards to the octal misinterpretation of .js - I just used this...

parseInt(parseFloat(nv))

and after testing with leading zeros, came back everytime with the correct representation.

hope this helps.

Your code should like this:

<span id="replies">8</span>


var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);

Hacks N Tricks

Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used

var currentValue = parseInt($("#replies").text(),10);
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );

I simply fixed your month issue, getMonth array start from 0 to 11.

parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.

var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);

Simply, add a plus sign before the text value

var newValue = +currentValue + 1;

You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.

You can use parseInt() method to convert string to integer in javascript

You just change the code like this

$("replies").text(parseInt($("replies").text(),10) + 1);