希望能够添加“/”或“,”符号以及传统的“+”符号。显然,“/”符号用于除法,但我想改变其目的。
function CalculateIMSUB(form) {
var Atext = form.input_A.value;
var Btext = form.input_B.value;
var val = form.val.value;
var A = eval(Atext);
var B = eval(Btext);
if (isNaN(A)) A = 0;
if (isNaN(B)) B = 0;
var answer = A - B;
form.Answer.value = answer;
form.input_A.value = form.input_A.value.replace(/\+/g, ",");
form.input_B.value = form.input_B.value.replace(/\+/g, ",");
}
function calculateAll() {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
CalculateIMSUB(forms[i]);
}
}
<form>
<INPUT TYPE=TEXT NAME="input_A" SIZE=15 />
<INPUT TYPE=TEXT NAME="input_B" SIZE=10 />
<INPUT TYPE="button" VALUE="+" name="SubtractButton" onclick="CalculateIMSUB(this.form)"
/>
<INPUT TYPE=TEXT NAME="Answer" SIZE=12 />
<input type="hidden" name="val" value="1221" />
</form>
答案 0 :(得分:2)
尝试实现类似的功能。没有eval
,只是数组。
function add( value ) {
return value.split(/[+,\/]/).reduce(function( a,b ) {
return +a + +b;
});
}
console.log( add('1+1+1') ); //=> 3
console.log( add('2,2,2') ); //=> 6
console.log( add('3/3/3') ); //=> 9