【发布时间】:2015-02-01 19:07:23
【问题描述】:
我想做的事:
我有一个 javascript 程序,当单击按钮时,它会从表单中的 4 个文本框中获取 4 个字符串,并将这些字符串输出到格式化的文本区域中。
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
上面的代码工作得很好,并且在我的程序范围内完全符合我的要求。
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
我试图用 try...catch 块完成的只是为了确保
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
实际上是数字。
try...catch 语句在我每次运行程序时触发,并不关心我在相应的文本框中输入了什么。我将非常感谢对此的任何和所有见解!
另外:我查看了这两个链接,但无法理解我的问题。 javascript parseInt return NaN for empty string http://www.w3schools.com/jsref/jsref_isnan.asp
【问题讨论】:
-
在这里使用
try/catch来解决这个本身不会抛出的简单问题是没有意义的。您可以直接使用if语句,代码会更简单且性能更好。我认为这里不需要例外。 -
提示:不要针对
== true测试布尔值。这是多余的;if (isNaN(errorhandle3) || isNaN(errorhandle2))读起来更好。 -
感谢两位的快速回复。我现在正在改变这些。
标签: javascript