日期:2014-05-16  浏览次数:20319 次

如何把字符串表达式转为可运算的表达式?
有字符串 expr = "sum = (A-B)*C";
sum ,A,B,C 为HTML中 <input id="sum, A , B ,C" value=""/> 的ID
我想通过JS处理后得到

total = ($("#A").val() - $("#B").val() )*$("#C").val();
$("#sum").val(total);


------解决方案--------------------
JScript code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
    var regx = /[^\/)%(\*\+=-]+/g;
    var expr = "sum = (A-B) * C";
    
    expr = expr.replace(regx,function($1){
        $1 = $1.replace(/\s*/g,"");
        return $1!=""?"document.getElementById('" + $1 + "').value":"";
    });
    window.onload = function(){
        eval(expr);
    }
</script>
</head>

<body>
    <input id="sum" type="text" value="" />
    <input id="A" type="text" value="3" />
    <input id="B" type="text" value="4" />
    <input id="C" type="text" value="5" />
</body>
</html>

------解决方案--------------------
HTML code
<input id="sum" type="text" value="" />
<input id="A" type="text" value="3" />
<input id="B" type="text" value="4" />
<input id="C" type="text" value="5" />
<script type="text/javascript">
var expr = "sum = (A-B) * C";
var sum = 0;
var A = $("#A").val();
var B = $("#B").val();
var C = $("#C").val();
window.eval('(' + expr + ')');
$("#sum").val(sum);
</script>