【问题标题】:Calculate equation like excel jquery像excel jquery一样计算方程
【发布时间】:2014-03-28 21:01:10
【问题描述】:

我有一个类似的 HTML,

 <table>
  <tr>
    <td><input type="text" data-column="A" value="5" data-row="1" /></td>
    <td><input type="text" data-column="B" value="2" data-row="1" /></td>

  </tr>
 <tr>
    <td><input type="text" value="7" data-column="A" data-row="2" /></td>
    <td><input type="text" value="9" data-column="B" data-row="2" /></td>
</tr>
<tr>
      <th><input type="text" data-column="A" data-row="3"  data-equation="A1+A2-B1" />      </th>
     <th><input type="text" data-column="B" data-row="3"  data-equation="B1+B2"  /></th>
   </tr>

 </table>  

和我的 javascript 一样

 $('input').each(function(){
 if($(this).attr('data-equation')!=undefined){
    var equation=$(this).attr('data-equation');
    $(this).val(calculate(equation))
 }
});

function calculate(equation){
  result=0;
  //calculate value and return,i dont know how to calculate
  return result;
} 

我需要根据data-equation计算值,在等式中,第一个元素参考data-column,第二个参考data-row强>

Fiddle Demo

【问题讨论】:

  • 您需要将表达式拆分为非字母数字字符并从那里开始。
  • 一个很好的问题,但它不会像执行一个简单的方程那么简单,你必须编写一个解析器来首先分离所有的运算符和操作数
  • 你的意思是第二个是指数据行吗?
  • @Nimnam1 是的............

标签: javascript jquery input


【解决方案1】:

如果有人仍在寻找类似的解决方案,我建议http://mathjs.org/

类似电子表格的简单示例:

jQuery(function($) {

  var calculate = function(n) {
    var expr = n.attr('data-equation')
      , ret  = expr;
    
    if (expr) {
      try {
        ret = math.eval(expr);
      } catch(e) {
        ret = 'Syntax error in equation!';  
      }
    }

    var obj = {};
    obj[n.attr('id')] = ret;
    math.import(obj, { override: true });

    return ret;
  };

  $.fn.equations = function() {

    $(this).each(function() {
      var n = $(this);

      n.focus(function() {
        n.val(n.attr('data-equation'));
      });

      n.blur(function() {
        n.attr('data-equation', n.val());
        n.attr('title', n.val());
        n.val(calculate(n));
      });

      if (!n.attr('data-equation')) {
        n.blur();
      }

      n.val(calculate(n));
    });

  };

  $('input').equations();

});
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Equations</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.5.1/math.min.js"></script>
  </head>
  <body>
    <p>A1: <input type="text" id="A1" value="2+2"/></p>
    <p>A2: <input type="text" id="A2" value="16"/></p>
    <p>A3: <input type="text" id="A3" value="A1+A2"/></p>
  </body>
</html>

【讨论】:

    【解决方案2】:

    带有子字符串:

    var math_it_up = {
        '+': function (x, y) { return x + y },
        '-': function (x, y) { return x - y },
        '*': function (x, y) { return x * y },
        '/': function (x, y) { return x / y }
    };
    
    $('input').each(function(){
        if($(this).attr('data-equation')!=undefined){
            var equation=$(this).attr('data-equation');
            $(this).val(calculate(equation));
        }
    });
    
    function calculate(equation){
        result=0;
        index=2;
    
        var value1 = $('input[data-column="'+equation.substring(0,1)+'"]
    [data-row="'+equation.substring(1,2)+'"]').val();
    
        result = parseInt(value1);
    
        while(equation.substring(index,index+1) !== "") {
            var operator = equation.substring(index, index+1);
    
            var value = $('input[data-column="'+equation.substring(index + 1, index+2)+'"]
    [data-row="'+equation.substring(index + 2, index+3)+'"]').val();
    
            result = math_it_up[operator](result, parseInt(value));
    
            index += 3;
        }
    
        return result;
    }
    

    我使用了来自How can I convert a string into a math operator in javascriptmath_it_up函数

    您可以通过添加您的运算符来扩大运算符(例如模数)。请注意,我没有检查 value1value 是否为有效数字。

    FIDDLE

    【讨论】:

    • math_it_up 绝对是映射操作的写入方式。不知道为什么我没想到。
    【解决方案3】:

    这是使用 eval 函数的另一种方法。用所有的数学运算完全实现这一点可能比它值得做的工作更多,所以在这里建议,但这里是一个简单的实现。 fiddle

    function calculate(equation){
        var vals = getValues(equation),
            operators = getOperators(equation),
            num1 = vals[0];
        for(var i=0; i<operators.length; i++){
            // simplistic you'll need to be more careful of order of operations
            // if you're going to be using things other than addition and subtraction
            num1 = calculateOperation(operators[i], num1, vals[i+1]);
        }
        return num1;
    }
    
    function calculateOperation(op, num1, num2){
        // add more ops as necessary
        if (op === '+'){
            return num1 + num2;
        } else if (op === '-'){
            return num1 - num2;
        }
    }
    
    function getValues(eq){
        // use regex because there might be more than one character denoting a row or column
        var column, row,
            operatorRegex = /[\+|\-]/;
            return eq.split(operatorRegex).map(function(identifier){
                column = identifier.replace(/[0-9]+/, "");
                row = identifier.replace(/[A-Za-z]+/, "");
                return parseInt($('[data-column="'+column+'"][data-row="'+row+'"]').val(), 10);
            });
    }
    
    function getOperators(eq){
         var ops = eq.split(/[A-Za-z0-9]+/);
         // remove the quotes and return
         return ops.slice(1, ops.length-1);
    }
    
    $('input').each(function(){
        if($(this).attr('data-equation')!=undefined){
            var equation=$(this).attr('data-equation');
            $(this).val(calculate(equation))
        }
    });
    

    【讨论】:

      【解决方案4】:

      你绝对可以用这个插件https://github.com/xsanisty/jquery-calx

      我在不久前创建了它,并且仍在维护它,但不是data-columndata-equation,而是使用data-celldata-formula 我的

      <form id="sheet">
          <input type="text" data-cell="A1" />
          <input type="text" data-cell="A2" />
          <input type="text" data-cell="A3" data-formula="A1*A2" />
      </form>
      

      只需要启动插件

      <script>
          $('#sheet').calx()
      </script>
      

      现在,它应该计算#sheet中定义的所有公式,你甚至可以在里面使用很多excel兼容的公式

      【讨论】:

        【解决方案5】:

        可以通过eval()函数完成:

        $(function(){
            $("input").each(function(){
                var col = $(this).data("column");
                var row = $(this).data("row");
                var val = $(this).val();
                var equation = $(this).data("equation");
        
                if(equation == undefined)
                {
                    eval(col+row+"="+val);
                }
                else
                {
                    $(this).val(eval(equation));
                }
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-09
          • 1970-01-01
          • 2021-12-29
          • 1970-01-01
          相关资源
          最近更新 更多