Javascript JQuery 乘法和加法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8035788/
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-24 04:28:55  来源:igfitidea点击:

JQuery multiply and add

javascriptjquery

提问by dennisbest

Let's say I have some numbers that I want to multiply and add.

假设我有一些数字要相乘和相加。

var a = 5;
var b = 10;
var c = 2;
var d = 3;

I want to sum b and c then multiply that by a, then add d. Easy right?

我想对 b 和 c 求和,然后乘以 a,然后加上 d。容易吧?

If if were a normal equation the formula would look like: (a * (b + c) + d)

如果是正规方程,则公式如下所示:(a * (b + c) + d)

But how do I do that in JQuery?

但是我如何在 JQuery 中做到这一点?

(Note: the reason for JQuery is that I'll be getting these numbers from fields and divs... and placing a total elsewhere, etc.)

(注意:JQuery 的原因是我将从字段和 div 中获取这些数字......并将总数放在其他地方,等等。)

回答by You Qi

convert your value into float or integer first before you do calculation. Example:

在进行计算之前,先将您的值转换为浮点数或整数。例子:

var a = parseFloat($(this).val());
var b = parseInt($("#b").attr("data"));

var c = (a+10)*b;
$("#result").text(c.toFixed(2));

回答by Marius

Just store the values in variables before you apply them to the equation:

在将值应用于方程之前,只需将值存储在变量中:

var a = +$("#input1")[0].value;
var b = +$("#input2")[0].value;
var c = +$("#input3")[0].value;
var d = +$("#input4")[0].value;

$("#output")[0].value = a*(b+c) + d;

The plus sign before the jquery function is there to force the string value into a Number value.

jquery 函数前的加号用于强制将字符串值转换为数字值。

回答by David Laberge

By default script language does not know type as intor float. So you can fix that by multiplying 1 to the value you expect to be a number.

默认情况下,脚本语言不知道类型为intfloat。因此,您可以通过将 1 乘以您希望成为数字的值来解决该问题。

var a = 5;
var b = 10;
var c = 2;
var d = 3; 

var total = a*1 * (b*1 + c*1) + d*1;

回答by Anand

Correct JQuery is 100% javascript.

正确的 JQuery 是 100% javascript。

Although, worth mentioning just use parseint() for the values that you get from text field

虽然值得一提的是,只需将 parseint() 用于您从文本字段中获得的值

回答by psynnott

You can still do the calculation using normal javascript, just refer to the contents using jQuery selectors if necessary.

您仍然可以使用普通的 javascript 进行计算,只需在必要时使用 jQuery 选择器参考内容。