jQuery 如何进行加法而不是串联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9081630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:18:35  来源:igfitidea点击:

How to make an addition instead of a concatenation

jquery

提问by Marc

I have an input button. I created for this input an attribute called "multiplicateur" which has the value of 1. When the button is clicked I have a .click()triggered. The function is suppose to get the value of the attribute and add 1 to it. So my output should be 2. Instead the output is 11. It seems the system makes a concatenation instead of an addition.

我有一个输入按钮。我为此输入创建了一个名为“multiplicateur”的属性,其值为 1。当单击按钮时,我.click()触发了一个。该函数假设获取属性的值并将其加 1。所以我的输出应该是 2。而不是输出是 11。似乎系统进行了串联而不是加法。

My HTML:

我的 HTML:

<input id="envoyer" type="submit" multiplicateur=1>

My JS:

我的JS:

$('#envoyer').click(function() {
    var ajaxData = $(this).attr('multiplicateur');
    alert(ajaxData + 1);
});

回答by xandercoded

ajaxDatais a string. Thus, you need to parseit to an integer...

ajaxData是一个string。因此,您需要将其解析integer...

 $('#envoyer').click(function() {
    var ajaxData = $(this).attr('multiplicateur');

    /* parse string to integer */
    alert(parseInt(ajaxData) + 1);

});

回答by S?ren Titze

You have to parse it first:

你必须先解析它:

    parseInt(ajaxData)+1;

回答by Muhammed Shihabudeen Labba A

In order to add value with decimal point, please use parseFloat(ajaxData)

为了用小数点添加值,请使用 parseFloat(ajaxData)

alert(parseFloat(ajaxData) + 1);

警报(解析浮动(ajaxData)+ 1);

回答by lilhamad

For substracting

对于减法

function removeFromQtt(){
             $("qty").value = parseInt($("qty").value)-1;
 }

For addition

用于添加

function add(){
             $("qty").value = parseInt($("qty").value)+1;
 }