jQuery的简单数学-除法 [英] Simple Maths with jQuery - division

查看:400
本文介绍了jQuery的简单数学-除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个div中有两个输入,我想将它们彼此分开.

I've got two inputs in a div that I want to divide one by the other.

<div>

<input type="number" id="a"> / <input type="number" id="b">

<input type="submit">

<p class="result">RESULT HERE</p> 

</div>

如何用jquery完成数学运算?

How can the maths of this be done with jquery?

推荐答案

这实际上取决于您希望何时进行计算,但是数学本身非常简单.只需使用标准的除法运算符/:

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);

我想这还取决于您是否只想支持整数除法(这就是为什么我使用parseInt的原因-必要时可以使用parseFloat.)

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).

此外,正如您对问题的评论中所述,label不是有效的属性.更好的选择是使用id,或者如果您需要使用任意命名的属性,请使用HTML5

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.

更新基于评论

正如您已经说过的那样,当您希望代码在单击按钮时运行时,您要做的就是绑定到click事件:

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:

$("#someButton").click(function() {
    //Do stuff when the button is clicked.
});

这篇关于jQuery的简单数学-除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆