如何parsingHTML表格单元格的行为,像Excel一样,使用JavaScript

我正在寻找一种方法来使HTML表格像使用JavaScript的Excel(JQuery首选)。 这是我的问题。 我做了这样一张桌子:

<table> <tr> <td id="A1">10</td> <td id="B1">10.5</td> </tr> <tr> <td id="A2">5</td> <td id="B2" formula="A1+B1+A2"></td> </tr> </table> 

每个td都有一个id,其中一些tds被添加了一个公式属性。 我想要计算这些公式,给公式的值给td。

在上面的表格中,我想指定B2值为25.5(B2 = A1 + B1 + A2)

看起来像这样:

 <td id="B2" formula="A1+B1+A2">25.5</td> 

有人可以给我一个线索吗? 谢谢。

PS:这是我发现的一些资源,但它们不能解决我的问题

  1. DOM上的类似电子表格的公式

  2. http://zaach.github.com/jison/docs/


非常感谢@palindrom。 我终于根据你的回答解决了我的问题。

这是我的代码:

  $("td[formula]").each(function(){ //1 get formula attribute var formula = $(this).attr('formula'); //2 use regex to make expression, with the surpport of "A122", "AB1" and more var expression = formula.replace(/([AZ]+[0-9]+)/g, "parseFloat(\$('#$1').html())") ; //3 eval the expression var result = eval( expression ); //4 set the value $(this).html(result); }); 

应该为简单的math工作,没有尝试:

 $("td[formula]").each( function() { this.html( eval( this.attr("formula").replace(/[az][0-9]/g, "\$('#$0').html()") ) ); } ); 

编辑:如果你有像公式一样的函数,将它们实现为JavaScript函数,他们也应该工作。

即使这太晚了,试试这个插件https://github.com/xsanisty/jquery-calx

我已经在其核心中使用jisonparsing器进行开发,它将像您想要的那样parsing数据公式属性中的公式

这是我写的一个html表格 ,其中为每一行计算一个公式(请参阅iframe源文件)。
该公式是用JavaScript编写的(尽可能复杂),其中[abc]用id = abc(来自标题的权重)和{abc}的单元格的值replace为同一列的单元格中的文本线。
列是可sorting的
权重是可以由用户修改的,他们被记住在一个cookie中。

希望这可以帮助。