Shi*_*jin 10 javascript jquery input
我有一个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>
Run Code Online (Sandbox Code Playgroud)
和我的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;
}
Run Code Online (Sandbox Code Playgroud)
我需要根据数据方程计算值.在等式中,第一个元素是数据列,第二个是数据行
小智 5
如果有人仍在寻找类似的解决方案,我建议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();
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
可以用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));
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2922 次 |
| 最近记录: |