2012-02-15 173 views
0

所以我設法把一些JavaScript(來自其他人的幫助)放在一起,這基本上是一個表單,它允許你改變一個項目的數量,並將其值添加到總數,如果其複選框被打勾文本字段在底部)。有人可以解釋這個JavaScript的工作原理嗎?

我明白其中的一些,它只是讓我困惑的更復雜的部分(比如邏輯)。有人可以通過我的代碼或者評論我的代碼的主要部分,這樣可以幫助我理解代碼是如何工作的。

<script type="text/javascript"> 
    function bump(which, bywhat) { 
     var form = document.items; 
     var qty = form["qty" + which]; 

     qty.value = Number(qty.value) + bywhat; 
     TotalCheckedValues(); // in case user bumped an already checked line 
    } 

    function TotalCheckedValues() { 
     var form = document.items; 
     var total = 0; 

     for (var n = 1; n <= 4; ++n) 
     { 
      if (form["cb"+n].checked) // if the checkbox of the item is ticked 
      { 
       total += form["cb"+n].value * form["qty"+n].value; // 
      } 
     } 

     form.Total.value = total.toFixed(2); 
    } 

    function validate(evt) { 
     var theEvent = evt || window.event; 
     var key = theEvent.keyCode || theEvent.which; 
     var regex = /[0-9]|\./; 

     key = String.fromCharCode(key); 

     if(!regex.test(key)) { 
      theEvent.returnValue = false; 
      if (theEvent.preventDefault) { 
       theEvent.preventDefault(); 
      } 
     } 
    } 
</script> 

</head> 

<body> 

<form name="items"> 

Item <input type="text" onkeypress='validate(event)'name="qty1" value="0"/> 
<input type="button" onclick="bump(1,1)" value="+"/> 
<input type="button" onclick="bump(1,-1)" value="-"/> 
<input type="checkbox" name="cb1" value="20.00" 
onClick="TotalCheckedValues()" />Service 1 (£20.00) <br /> 

Item <input type="text" onkeypress='validate(event)' name="qty2" value="0"/> 
<input type="button" onclick="bump(2,1)" value="+"/> 
<input type="button" onclick="bump(2,-1)" value="-"/> 
<input type="checkbox" name="cb2" value="20.00" 
onClick="TotalCheckedValues()" />Service 2 (£20.00) <br /> 

Item <input type="text" onkeypress='validate(event)' name="qty3" value="0"/> 
<input type="button" onclick="bump(3,1)" value="+"/> 
<input type="button" onclick="bump(3,-1)" value="-"/> 
<input type="checkbox" name="cb3" value="20.00" 
onClick="TotalCheckedValues()" />Service 3 (£20.00) <br /> 

Item <input type="text" onkeypress='validate(event)' name="qty4" value="0"/> 
<input type="button" onclick="bump(4,1)" value="+"/> 
<input type="button" onclick="bump(4,-1)" value="-"/> 
<input type="checkbox" name="cb4" value="10.00" 
onClick="TotalCheckedValues()" />Service 4 (£10.00) <br /> 

Total: <input type="text" name="Total" readonly size="5" /> 

<input type="reset" name="reset" value="Clear Selected"> 

</form> 

</body> 
</html> 
+0

那麼你想解釋哪個部分?如果它明智地縮進,它也會更容易。 – 2012-02-15 13:51:27

+0

對不起,我不熟悉使用這個網站,所以在發佈時我有點困惑。基本上這三個函數,代碼中的「凹凸」部分是我最困惑的部分。 – 2012-02-15 14:00:43

回答

1

首先,我不知道這是那種javascript中,你應該學習的。但是,我會盡力給你一些提示

有3個功能:validatebumpTotalCheckedValues

Validate是最容易理解的。請注意每個onkeypress屬性中對此函數的調用。調用Validate來驗證剛被按下鍵入輸入的鍵是0到9(包含)還是點。 (正則表達式檢查)

bump已記錄每個項目上的+和 - 按鈕的點擊次數(以跟蹤數量)。它依靠對document.items表格的呼叫,該表格的items以升序排列,並以其名稱中的號碼(第一項爲name="qty1")標識。該函數將參數指定爲項目的索引和增加或減少其值的數量(bump(3,1)用於第3項的+按鈕,即:取第3項並將其值加1)。該功能與所述第三功能

TotalCheckedValues一個呼叫結束是否有重新計算的總量(sum(quantity*price)每個項目,如果該複選框被選中用於此項目)。此功能retriver的項目,重複這些,如果選中該複選框檢查,如果是,採取價格和數量,繁殖它們,並將它們添加到總

0
// Also going to be cleaning up the code a little - no offense, I'm just anal 
// One more note: I'll be specifying types in my function documentation - but remember 
// that JS doesn't really *do* types 


/** 
* Grab a quantity and increase it by a given value 
* @param int which Number of the field to target (comes out as 'qty1/2/3/4/etc') 
* @param int bywhat Number to increase the value found with 'which' by 
*/ 
function bump(which, bywhat) { 
    // Find the form child named 'qtyn', where n is a number 
    // Notice only one var definition here - no need to define form if 
    // you can just get to your target element/attribute/etc. 
    var qty = document.items['qty' + which].value; 

    qty = Number(qty) + bywhat; // Add bywhat to the form value 
    TotalCheckedValues(); // in case user bumped an already checked line 
} 

/** 
* Iterate through all check boxes (cb) on the form and multiply quantities (qty) 
* against values on checked boxes. 
*/ 
function TotalCheckedValues() { 
    // Some consider it best practice to put all vars in the top of the method, 
    // in a comma-separated list using one "var" keyword. 
    var form = document.items, 
     total = 0, 
     checkbox = null, 
     n = 1; 

    for(n; n <= 4; ++n) 
    { 
     checkbox = "cb"+n; // make your code easier to read 
     if(form[checkbox].checked) // if the checkbox of the item is ticked 
     { 
      // If the checkbox is checked, multiply it's value to that of each qty field 
      total += form[checkbox].value * form["qty"+n].value; 
     } 
    } 

    form.Total.value = total.toFixed(2); // Shorten 'total' to 2 decimal places 
} 

/** 
* Test for a valid key 
* @param event evt The key-related event 
*/ 
function validate(evt) { 
    /* 
    * In javascript, the OR operator || is used as a way of setting defaults. So, 
    * keep trying values until one that's considered "true" is found: 
    * var something = false; 
    * var foo = null; 
    * var bar = 'abc'; 
    * var which = something || foo || bar; // value of 'which' is 'abc' 
    */ 
    var theEvent = evt || window.event, 
     key = theEvent.keyCode || theEvent.which, 
     regex = /[0-9]|\./; // Regex that matches 0-9 and '.' 

    key = String.fromCharCode(key); // Convert from key code to something usable 

    // I almost think you could do... 
    // var ... key = String.fromCharCode(theEvent.keyCode || theEvent.which) 
    // but I'm not sure. 

    // If our key event's code doesn't pass our regex test 
    if(!regex.test(key)) { 
     theEvent.returnValue = false; 

     if(theEvent.preventDefault) 
      theEvent.preventDefault(); 
    } 
} 

其他一些建議

一些其它指針我想與大家分享,也許只是一些建議考慮:

  • 依靠硬編碼的限制(在對TotalCheckedValues循環「4」())使你的代碼少重用。相反,你應該遍歷所有匹配的子節點到父節點。有了jQuery,它就像$('#MyFormId input[type="checkbox"]).each(...)這使得代碼更加靈活,並且不需要僅僅因爲添加了另一個複選框而進行更新。

  • 在您的表單元素上使用ID來使選擇更明顯 - 依靠文檔[名稱]是好的,但可能無法在任何地方播放。

  • 其中bywhatEVT - 變量名是偉大的,因爲他們可以是任何東西,所以決定要打電話給你的變量時,記住這一點。描述性名稱1)幫助您記住當您在2個月後回到代碼時發生的情況,以及2)幫助任何必須通過您的代碼(無論出於何種原因)瞭解正在發生的事情的人。

  • 一致性是關鍵:你的函數名在風格混合:bumb VS TotalCheckedValues VS 驗證 - 你應該選擇適合您的代碼的一種方式,並堅持下去。

  • 如果你真的想要挑剔你的代碼並讓你哭泣,請訪問JSLint。但只是閱讀「JSLint如何工作?」關於如何以及爲什麼他們挑選代碼的某些部分可能對於學習Javascript和JS的一些最佳實踐©有價值。

0

注意:我通過寫這個得到了大約一半的時間,並且發現人們已經回答 - 對任何重複都道歉,但我想完成我開始的任務!

1. '凸點' 功能

該函數接受兩個參數:

  • '其中' 是一個數字,這有助於識別特定文本字段。
  • 'bywhat'是一個數字,表示該字段的數量增加/減少的數量 - 或使用此處使用的術語 - 「顛簸」。

var form = document.items;

該函數首先獲取全局文檔對象中的所有項目,您可以從任意位置訪問該項目。

var qty = form ['qty'+ which];

此代碼然後嘗試該陣列,其具有「數量」的名稱在訪問特定項加其中參數。當你在這種情況下使用'+'運算符時,你要向一個數字(,其中)添加一個字符串('qty'),你最終會得到一個字符串;例如'qty3'。

qty.value = Number(qty.value)+ bywhat;

的「的值數量+ 其中」輸入元件然後被設置,通過取當前值,將其轉換爲一個數字,然後加入bywhat參數到它。在這種情況下,當您使用'+'運算符時,您需要在數字中添加數字,然後執行數學計算;例如1 + 2 = 3.

TotalCheckedValues();

然後代碼調用TotalCheckedValues函數,該函數似乎計算總數(我們將在下面介紹)。

2。'TotalCheckedValues'函數

該函數在每個'bump'函數調用之後調用,每調用一個複選框也被調用/取消選中。

var form = document.items;

功能再次得到一個數組的所有全球文檔對象的項目,你可以從任何地方訪問的開始。

var total = 0;

然後,該函數定義了一個「總」變量,它被設置爲零。

的「for」循環

該代碼隨後循環四次,一次用於每個HTML中的輸入/按鈕/複選框組。它會嘗試獲取每個組的複選框元素,然後檢查該複選框是否被選中。如果是,則複選框值(這是價格)乘以文本字段的數量值,並添加到「總計」變量。 '+ ='操作符在此將右側的值添加到現有值,而不是覆蓋現有值。

form.Total.value = total.toFixed(2);

然後函數嘗試在document.items數組中使用名稱'Total'查找元素,使用點符號而不是您之前見過的括號符號(例如form ['qty']) 。該元素的值使用上面for循環生成的總數來設置。的toFixed(2)函數可以在數字被用來返回與小數位的給定數目的數目的字符串表示 - 在這種情況下,2。

3.「驗證」功能

var theEvent = evt || window.event;

創建包含已提出的事件對象的變量。它檢查傳入的evt參數是否有事件對象 - 如果它爲空或未定義,則使用window.event事件對象。

var key = theEvent.keyCode || theEvent.which;

試圖確定按下哪個鍵來觸發變量的事件,並將其存儲。

var regex = /[0-9]|./;

定義正則表達式模式,這將這些值匹配0到9,和點的字符。

key = String.fromCharCode(key);

嘗試檢索關鍵,這...

如果(!正則表達式的字符串。測試(密鑰))

...然後針對正則表達式進行測試。如果test()函數匹配模式,則返回true;如果不匹配,則返回false。如果正則表達式匹配失敗,則運行此'if'語句中的其餘代碼;它爲事件設置一個返回值,並在不停止向其他偵聽器傳播事件的情況下取消事件(preventDefault)。

希望JavaScript功能的演練有所幫助!

相關問題