使用jquery添加两个变量

问题描述:

var a = 1;
var b = 2;
var c = a+b;

c 将显示为 12 ;但我需要 3

c will show as 12; but I need 3

我如何使用jQuery做到这一点?

How do I do it using jQuery?

看起来你有字符串而不是数字,你需要 parseInt() parseFloat() (如果它们可能是小数),如下所示:

It looks like you have strings and not numbers, you need parseInt() or parseFloat() (if they may be decimals) here, like this:

var a = "1";
var b = "2";
var c = parseInt(a, 10) + parseInt(b, 10);
//or: var c = parseFloat(a) + parseFloat(b);

你可以在这里测试差异,值得注意的是这些不是jQuery而是基础JavaScript函数,所以这不依赖于jQuery库。

You can test the difference here, it's worth noting these are not jQuery but base JavaScript functions, so this isn't dependent on the jQuery library in any way.