简体   繁体   English

JQuery繁殖并添加

[英]JQuery multiply and add

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. 我想将b和c相加然后乘以a,然后加上d。 Easy right? 容易吗?

If if were a normal equation the formula would look like: (a * (b + c) + d) 如果if是正规方程式,公式将如下所示:(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中获取这些数字......并在其他地方放置等等)

convert your value into float or integer first before you do calculation. 在计算之前,首先将您的值转换为float或integer。 Example: 例:

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

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

By default script language does not know type as int or float . 默认情况下,脚本语言不知道类型为intfloat So you can fix that by multiplying 1 to the value you expect to be a number. 因此,您可以通过将1乘以您希望为数字的值来解决此问题。

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

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

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函数之前的加号用于强制将字符串值转换为Number值。

Correct JQuery is 100% javascript. 正确的JQuery是100%的javascript。

Although, worth mentioning just use parseint() for the values that you get from text field 虽然,值得一提的是只使用parseint()来获取从文本字段获得的值

你仍然可以使用普通的javascript进行计算,如果需要,只需使用jQuery选择器来引用内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM