在文本字段中使用Javascript运行方程式 [英] Running an equation with Javascript from a text field
问题描述
我正在尝试创建一个简单的在线计算器,该计算器可以使用Javascript运行基本计算.
I am trying to create a simple online calculator that can run basic calculations in Javascript.
我设法创建了接口,以便将数字和运算符存储在表单字段中.
I have managed to create the interface so that numbers and operators and stored in a form field.
我想做的就是将form字段中的值传递给一个函数,该函数将计算form字段的总数.
What I would like to be able to do is pass the values within the form field to a function that will calculate the total of the form field.
form字段可以包含任何内容,从简单的10 + 10到使用方括号的更复杂的方程式.使用的运算符是+-*/
The form field could contain anything from a simple 10 + 10 to more complex equations using brackets. The operators in use are +-*/
是否可以将form字段传递给javascript函数,该javascript函数可以识别运算符并执行对值的运算功能.
Is it possible to pass the form field to a javascript function that can recognize the operators and the perform the function of the operation on the values.
文本字段中的可能值为:
A possible value in the text field would be:
120/4 + 130/5
120/4+130/5
然后,该函数应返回56作为答案.当我知道类似小提琴中的值 http://jsfiddle.net/DhqGB/
The function should then return 56 as the answer. I have done this in javascript when I know the values like in this fiddle http://jsfiddle.net/DhqGB/
我想做的就是将完整的值"120/4 + 130/5"传递给该函数,它能够提取数字和运算符以创建总数.
What I would like to be able to do is pass the full value "120/4+130/5" to the function and it be able to extract the numbers and operators to create the total.
有人对如何完成甚至可能做到有任何想法吗?这可能会变得更加复杂,可能需要在括号(120/4)+(130/5)"中传递值
Does anyone have any ideas on how this could be done or if it is even possible? this may get more complex where I may need to pass values in parentheses "(120/4)+(130/5)"
推荐答案
eval
有什么用?
将calc
视为文本字段的ID.然后
consider calc
as the id of textfield. then
$('#calc').change(function(e){
alert(eval($(this).val()));
})
但是请记住在处理之前先验证输入.
but remember to validate input before processing.
这篇关于在文本字段中使用Javascript运行方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!