3

我是javascript的新手。所以我有疑问

对于以下代码,如何通过在按下数字或特殊字符时提醒用户来更改功能?

function onlyAlphabets(e, t) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        } else if (e) {
            var charCode = e.which;
        } else {
            return true;
        }

        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
            return true;
        else
            return false;
    } catch (err) {
        alert(err.Description);
    }
}
4

2 回答 2

1

我认为你的问题的答案在stackoverflow中已经可用

上面链接的一些摘录: 我在这里更新了小提琴, 你可以输入任何字符并获得所需的警报。

$(function() {
    var $kp = $('#keyPress');
    var $kd = $('#keyDown');
    var $ku = $('#keyUp');

    var _to_ascii = {
        '188': '44',
        '109': '45',
        '190': '46',
        '191': '47',
        '192': '96',
        '220': '92',
        '222': '39',
        '221': '93',
        '219': '91',
        '173': '45',
        '187': '61', //IE Key codes
        '186': '59', //IE Key codes
        '189': '45'  //IE Key codes
    }

    var shiftUps = {
        "96": "~",
        "49": "!",
        "50": "@",
        "51": "#",
        "52": "$",
        "53": "%",
        "54": "^",
        "55": "&",
        "56": "*",
        "57": "(",
        "48": ")",
        "45": "_",
        "61": "+",
        "91": "{",
        "93": "}",
        "92": "|",
        "59": ":",
        "39": "\"",
        "44": "<",
        "46": ">",
        "47": "?"
    };

    $(document).on('keydown', function(e) {
        var c = e.which;

        if (_to_ascii.hasOwnProperty(c)) {
            c = _to_ascii[c];
        }

        //for Chracters
        if (!e.shiftKey && (c >= 65 && c <= 90)) {
            c = String.fromCharCode(c + 32);
            alert("chracters");
        } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
            c = shiftUps[c];
            alert("Special chracters");
        } else {
            c = String.fromCharCode(c);
            alert("Numbers");
        }

        $kd.val(c);
    }).on('keypress', function(e) {
        $kp.val(String.fromCharCode(e.which));
    });



});
于 2013-09-10T11:05:58.773 回答
0
function numberSpl(e){
 try {
    if (window.event){
    var charCode = window.event.keyCode;
     }
   else if (e) {
    var charCode = e.which;
   }
   else { return true; }
    // NUMBER CHECK
     num = /[0-9.]/.test(charCode);
   //CHARACTER CHECK
     splChar = /[!@#$%^&*]/.test(charCode);
    if(num === true && splChar === true)
      return true;
   else
    return false;
      }
     catch (err) {
   alert(err.Description);

}

于 2013-09-10T11:00:30.567 回答