2

我正在从“JavaScript Bible”一书中学习javascript,但我遇到了一些困难。我试图理解这段代码:

function checkIt(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        status = "This field accept only numbers."
        return false
    }
    status = ""
    return true
}

有人可以给我解释一下吗?

4

2 回答 2

3

我假设您只是想让我们解释一下代码的作用。如果是这样,请参见下文:

// Create a function named checkIt, which takes an argument evt.
function checkIt(evt) {

    // If the user has passed something in the argument evt, take it.
    // Else, take the window.event as evt.
    evt = (evt) ? evt : window.event;

    // Get the Character Code. It can be either from evt.which or evt.keyCode,
    // depending on the browser.
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    // If the Character is not a number, the do not allow the user to type in.
    // The reason for giving 31 to 48 and greater than 57 is because, each key
    // you type has its own unique character code. From 31 to 48, are the numeric
    // keys in the keyboard.
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {

        // Give a status informing the user.
        status = "This field accept only numbers.";

        // Prevent the default action of entering the character.
        return false;
    }

    // Clear the status
    status = "";

    // Allow the user to enter text.
    return true;
}

ASCII 代码参考


(来源:cdrummond.qc.ca


(来源:cdrummond.qc.ca

PS:我编辑了您的代码,添加了缺少的分号。;

于 2012-10-15T04:59:51.563 回答
0

它基本上说:

evt = (evt) ? evt : window.event

如果“evt”是一个值,则继续,否则将 window.event 分配给 evt。这是 if 语句的简写

var charCode = (evt.which) ? evt.which : evt.keyCode

创建一个新变量,如果存在 evt (“which”) 的子变量,则将其分配给新创建的变量,如果不分配“evt”子变量;“关键代码”

if (charCode > 31 && (charCode < 48 || charCode > 57)){
            status = "This field accept only numbers."
            return false
}

如果 charcode 大于 31 并且 charcode 小于 48 或大于 57,则继续。将字符串分配给 var status 并返回 false 终止函数(意味着出现问题)

status = ""
return true

如果上述语句一切顺利,则将任何空字符串分配给“状态”并返回 true,这意味着一切顺利

于 2012-10-15T05:00:27.193 回答