是否可以像數組一樣創建函數? ,以便以下功能可以變得簡單並易於編輯。製作一個javascript數組函數
function q1() {
var theForm = document.forms["contact-form"];
var quantity = theForm.elements["q1"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
function q2() {
var theForm = document.forms["contact-form"];
var quantity = theForm.elements["q2"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
function q3() {
var theForm = document.forms["contact-form"];
var quantity = theForm.elements["q3"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
現在我改變了這樣的 GetQuantity()用於獲取從數量字段中的值。例如q_A01 .. GetPrice()用於獲取只讀值Price字段。例如calculate_total()用於計算總價格並返回字段ID「Total」。p_A01 .. calculateTotal()用於計算總價格並返回字段ID「Total」。
function GetQuantity(e) {
var theForm = document.forms["contact-form"];
var quantity = theForm.elements[e];
var howmany =0;
if(quantity.value!=0) {
howmany = parseInt(quantity.value); }
return howmany;
}
function GetPrice(e) {
var theForm = document.forms["contact-form"];
var price = theForm.elements[e];
var howmany =0;
if(price.value!=0) {
howmany = parseInt(price.value); }
return howmany;
}
function calculateTotal()
{
var cakePrice =
GetPrice(p_A01)*GetQuantity(q_A01)+
GetPrice(p_A02)*GetQuantity(q_A02)+
GetPrice(p_A03)*GetQuantity(q_A03)+
GetPrice(p_F11)*GetQuantity(q_F11);
var Totalordered = document.getElementById ("Total");
Totalordered.value = cakePrice;
}
你當然可以寫得更短,也許只是'function fetch(){return 0}',因爲它們都返回相同的東西嗎? – adeneo
當只有一件事情發生變化時,一個「switch」或甚至一個對象查找表會更合適。 – dandavis
我想你的函數應該返回'return quantity.length'而不是'howmany' – RomanPerekhrest