Javascript jQuery 的简单数学 - 除法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7799438/
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
Simple Maths with jQuery - division
提问by Stuart Robson
I've got two inputs in a div that I want to divide one by the other.
我在一个 div 中有两个输入,我想将它们除以另一个。
<div>
<input type="number" id="a"> / <input type="number" id="b">
<input type="submit">
<p class="result">RESULT HERE</p>
</div>
How can the maths of this be done with jquery?
这个数学如何用 jquery 完成?
回答by James Allardice
It really depends when you want the calculation to take place, but the maths itself is incredibly simple. Just use the standard division operator, /
:
这实际上取决于您希望何时进行计算,但数学本身非常简单。只需使用标准除法运算符, /
:
var num1 = $("input[label='a']").val(),
num2 = $("input[label='b']").val(),
result = parseInt(num1, 10) / parseInt(num2, 10);
$(".result").text(result);
I guess it also depends if you only want to support integer division (that's why I've used parseInt
- you could use parseFloat
if necessary).
我想这也取决于您是否只想支持整数除法(这就是我使用的原因parseInt
- 您可以parseFloat
在必要时使用)。
Also, as mentioned in the comments on your question, label
is not a valid attribute. A better option would be to use id
, or if you need to use an arbitrarily named attribute, use HTML5 data-*
attributes.
此外,正如对您的问题的评论中所述,label
不是有效的属性。更好的选择是使用id
,或者如果您需要使用任意命名的属性,请使用 HTML5data-*
属性。
Updatebased on comments
根据评论更新
As you have stated that you want the code to run when a button is clicked, all you need to do is bind to the click
event:
正如您所说,您希望在单击按钮时运行代码,您需要做的就是绑定到click
事件:
$("#someButton").click(function() {
//Do stuff when the button is clicked.
});
回答by Jason Barry
You're mixing your markup with your logic. You can't divide HTML elements with each other they are for structural presentation only. Instead, you have to pull their values with javascript, apply the math, and update the HTML with the resulting value.
您将标记与逻辑混合在一起。您不能将 HTML 元素彼此分开,它们仅用于结构表示。相反,您必须使用 javascript 提取它们的值,应用数学,并使用结果值更新 HTML。