簡體   English   中英

有人可以解釋此JavaScript的工作方式嗎?

[英]Can someone explain how this JavaScript is working?

因此,我設法整理了一些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>

首先,我不確定那是您應該從中學習的javascript。但是,我會盡力給您一些提示

有3個函數: validatebumpTotalCheckedValues

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

bump以記錄每個項目上+和-按鈕的點擊次數(以跟蹤數量)。 它依賴於對document.items表單的調用,該表單給出其items ,這些items按升序命名,並由其名稱中的數字標識(第一個項目的name="qty1" )。 該函數將項目的索引以及增加或減少其值的數量作為參數bump(3,1)第3個項目的+按鈕的bump(3,1)表示:取第3個項目並將其值加1)。 該函數以對第三個函數的調用結束

TotalCheckedValues可以在其中重新計算總金額(如果選中了此項目的復選框,則為每個項目的sum(quantity*price) )。 此功能檢索項目,對其進行迭代,檢查復選框是否被選中,如果是,則取價格和數量,相乘並將其加到總計中

// 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()中for循環中的“ 4”)使代碼的可重用性降低。 相反,您應該將所有匹配的子代迭代到父節點。 使用jQuery,它就像$('#MyFormId input[type="checkbox"]).each(...)這樣的代碼,它使代碼變得靈活並且不需要更新,因為您添加了另一個復選框。

  • 在表單元素上使用ID可以使選擇更加明顯-依靠document [name]是可以的,但可能並非在所有地方都能很好地發揮作用。

  • 其中 ,bywhat,EVT -變量名是偉大的,因為他們可以是任何東西,所以決定要打電話給你的變量時,記住這一點。 描述性名稱1)幫助您記住兩個月后返回代碼時發生的事情,以及2)幫助出於任何原因必須仔細閱讀代碼的其他人以了解發生了什么。

  • 一致性是關鍵:函數名混合使用: bumb vs TotalCheckedValues vs validate-您應該為代碼選擇一種方式並堅持下去。

  • 如果您確實想要一些東西可以竊取您的代碼,並且讓您哭泣,請隨時訪問JSLint。 但是只要閱讀“ JSLint如何工作?”即可。 關於如何以及為什么它們將代碼的某些部分分開的頁面,對於學習Javascript和JS的一些最佳實踐©而言非常有價值。

注意:撰寫本文的過程已經差不多完成了一半,發現人們已經回答了。對於任何重復,我都表示歉意,但是我想完成我開始的工作!

1.“凹凸”功能

此函數接受兩個參數:

  • 哪個 ”是有助於識別特定文本字段的數字。
  • bywhat ”是一個數字,指示字段中的數字要增加/減少多少(或使用此處使用的術語)“顛簸”。

var form = document.items;

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

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

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

qty.value =數字(qty.value)+多少;

然后通過獲取當前值,將其轉換為數字,然后在其上添加bywhat參數,來設置輸入元素“ qty + where ”的值。 在這種情況下,當您使用'+'運算符時,您要將數字加到數字上,就需要進行數學計算; 例如1 + 2 = 3。

TotalCheckedValues();

然后,代碼調用TotalCheckedValues函數,該函數似乎用於計算總數(我們將在下一部分介紹)。

2.'TotalCheckedValues'函數

每次“凹凸”函數調用之后都會調用此函數,並且每次選中/取消選中復選框時也會調用此函數。

var form = document.items;

該函數再次從獲取全局文檔對象中所有項目的數組開始,您可以從任何位置訪問該數組。

var total = 0;

然后,該函數定義一個“總計”變量,該變量設置為零。

“ for”循環

然后,該代碼循環四次,對於HTML中的每個輸入/按鈕/復選框組,循環一次。 它嘗試獲取每個組的復選框元素,然后檢查是否已選中該復選框。 如果是,則復選框值(即價格)乘以文本字段的數量值,然后添加到“總計”變量中。 這里的“ + =”運算符將其右側的值添加到現有值,而不是覆蓋現有值。

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

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

3.“驗證”功能

var theEvent = evt || window.event;

創建一個包含已引發的事件對象的變量。 它檢查傳遞的evt參數中是否有事件對象-如果它為null或未定義,則使用window.event事件對象。

var key = theEvent.keyCode || theEvent。哪個;

嘗試確定按下了哪個鍵來觸發事件並將其存儲在變量中。

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

定義一個正則表達式模式,它將匹配值零到九以及點字符。

鍵= String.fromCharCode(鍵);

嘗試從密鑰中檢索字符串,這會...

if(!regex.test(key))

...然后針對正則表達式進行測試。 如果test()函數與模式匹配,則返回true;否則,返回false。 如果正則表達式匹配失敗,則運行“ if”語句中的其余代碼; 它設置事件的返回值,並取消事件(preventDefault),而不停止將事件傳播到其他偵聽器。

希望JavaScript函數演練對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM