我想要做的事:「嘗試... catch」塊不parseInt函數()工作
我有一個JavaScript程序,一個按鈕被按下時,發生在4串4文本框,並將這些字符串輸出爲格式化的textarea。
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!");
}
}
我試圖用努力完成... 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
這是沒有意義在這裏使用'嘗試/ catch'周圍的東西這個簡單的通過本身扔不比較。你可以直接使用'if'語句,代碼會更簡單,性能更好。我在這裏看不到任何例外情況。 – jfriend00 2014-12-04 01:56:45
提示:不要針對'== true'測試布爾值。這是多餘的; if(isNaN(errorhandle3)|| isNaN(errorhandle2))'讀得更好。 – Ryan 2014-12-04 02:00:44
謝謝你們的快速回復。我現在正在改變這些。 – Fishbones 2014-12-04 02:09:11