Javascriptを使用してExcelのように動作するhtmlテーブルを作成する方法を探しています(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 があり、それらの td の一部には式属性が追加されています。そして、それらの式を計算し、式の値を td に渡します。
上の表では、 B2値25.5(B2=A1+B1+A2)を割り当てたいと思います。
こんな風に見える:
<td id="B2" formula="A1+B1+A2">25.5</td>
誰でも私に手がかりを与えることができますか?ありがとう。
PS:ここに私が見つけたいくつかのリソースがありますが、それらは私の問題を解決しません
どうもありがとう@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(/([A-Z]+[0-9]+)/g, "parseFloat(\$('#$1').html())") ;
//3 eval the expression
var result = eval( expression );
//4 set the value
$(this).html(result);
});