简体   繁体   English

添加数字时IE中的JavaScript问题

[英]JavaScript issue in IE when adding numbers

I have a simple form, with 5 textboxes and 3 answers (also textboxes). 我有一个简单的表格,有5个文本框和3个答案(也有文本框)。 The form calculates a result for the user with number inputs. 该表格使用数字输入为用户计算结果。 My problem is my calculation does not work in IE, but works fine in both Chrome and Firefox. 我的问题是我的计算在IE中不起作用,但在Chrome和Firefox中都能正常工作。

What's wrong? 怎么了?

Here is my function: 这是我的功能:

function addNumbers()
{
    var val1 = Number(document.getElementById("value1").value);
    var val2 = Number(document.getElementById("value2").value);
    var val3 = Number(document.getElementById("value3").value);
    var val4 = Number(document.getElementById("value4").value);
    var val5 = Number(document.getElementById("value5").value);
    var val6 = '100';
    var ansD1 = document.getElementById("answer1");
    ansD1.value = Number((val1 * val2) * (val4 / val6));
    var ansD2 = document.getElementById("answer2");
    ansD2.value = Number((val1 * val3) * (val5 / val6));
    var ansD3 = document.getElementById("answer3");
    ansD3.value = Number (ansD1.value - ansD2.value);
}

Change this line: 更改此行:

var val6 = '100';

to this: 对此:

var val6 = 100;

You want all your values to be actual numbers (not strings) so you can do math on them. 您希望所有值都是实际数字(而不是字符串),以便可以对它们进行数学运算。

Also, you don't need the Number() in these lines because the result of the numeric math is already a number. 另外,由于这些数字数学运算的结果已经是一个数字,因此您无需在这些行中使用Number()。 Plus the assignment to the answer fields is just going to convert the result to a string anyway: 再加上对答案字段的分配,无论如何都将结果转换为字符串:

ansD1.value = Number((val1 * val2)*(val4/val6));

They can just be this: 他们可以是这样的:

ansD1.value = (val1 * val2)*(val4/val6);

The modified code works fine in IE here: http://jsfiddle.net/jfriend00/5WFRA/ . 修改后的代码可在IE上正常运行: http : //jsfiddle.net/jfriend00/5WFRA/

代替Number使用parseInt ,否则将它们视为字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM