使用 jQuery 进行简单数学 - 除法
我在 div 中有两个输入,我想将其除以另一个。
<div>
<input type="number" id="a"> / <input type="number" id="b">
<input type="submit">
<p class="result">RESULT HERE</p>
</div>
如何用 jquery 来完成这个数学运算?
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>
How can the maths of this be done with jquery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这实际上取决于您希望计算何时进行,但数学本身非常简单。只需使用标准的 除法运算符,
/
:我想它也是取决于您是否只想支持整数除法(这就是我使用
parseInt
的原因 - 如果需要,您可以使用parseFloat
)。另外,正如您问题的评论中所提到的,
label
不是有效的属性。更好的选择是使用id
,或者如果您需要使用任意命名的属性,请使用 HTML5data-*
属性。根据评论更新
正如您所说,您希望在单击按钮时运行代码,您所需要做的就是绑定到
click
事件:It really depends when you want the calculation to take place, but the maths itself is incredibly simple. Just use the standard division operator,
/
:I guess it also depends if you only want to support integer division (that's why I've used
parseInt
- you could useparseFloat
if necessary).Also, as mentioned in the comments on your question,
label
is not a valid attribute. A better option would be to useid
, or if you need to use an arbitrarily named attribute, use HTML5data-*
attributes.Update based 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:您将标记与逻辑混合在一起。您不能将 HTML 元素彼此分开,它们仅用于结构演示。相反,您必须使用 JavaScript 提取它们的值,应用数学计算,并使用结果值更新 HTML。
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.