1

我知道这个问题到处都是,但这让我发疯了!!!

这是我的代码:

$(document).ready(function () {

        $('#MainContent_LoginUser_Password').keypress(function (e) {

            noCapsLock($('#MainContent_LoginUser_Password'), e, "Please turn off Caps Lock");
        });

    });
function noCapsLock(o, e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
    alert(str);
    o.val('');

}     
}

我正在尝试清除具有给定 ID 的文本框的值。上面的代码清除了文本,但是当按下一个新键时,会显示该键的值(大写字母)。我已经尝试了 change()、keyup()、keydown() 函数,但它们似乎仍然没有清除最后输入的值的文本框。

任何帮助将不胜感激。谢谢!

4

3 回答 3

1

你只需要添加一个event.preventDefault();

您可能还希望将您的函数放在闭包内,这样它就不是全局的,并且您不需要在方法内再次重新找到 html 元素:

$(document).ready(function () {

    var noCapsLock = function(o, e, str) {
        var s = String.fromCharCode(e.which);
        if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
            alert(str);
            o.val('');
            e.preventDefault();
        }     
    }    

    $('#MainContent_LoginUser_Password').keypress(function (e) {
        noCapsLock($(this), e, "Please turn off Caps Lock");
    });
});

为了踢球,我还将您的代码制作成一个 jQuery 插件,您可以轻松地将其应用于任何元素(它不会删除值,只是停止按键):

(function($) {
    $.fn.noCapsLock = function(message) {
        this.keypress(function (e) {
            var char = String.fromCharCode(e.which);
            if (char.toUpperCase() === char && char.toLowerCase() !== char && !e.shiftKey) {
                window.alert(message);
                e.preventDefault();
            }         
        });
    };
})(jQuery);

像这样申请:

$(document).ready(function () {
    $('#MainContent_LoginUser_Password').noCapsLock('Please turn off Caps Lock!');
});
于 2013-03-18T21:46:11.127 回答
1

您只需使用以下命令取消活动e.preventDefault();

function noCapsLock(o, e, str) {
    var s = String.fromCharCode(e.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        e.preventDefault();
        alert(str);
        o.val('');
    }     
}
于 2013-03-18T21:46:37.953 回答
1

在您的情况下,我不会清除文本框;如果用户输入小写的长文本,然后点击 CapsLock 然后继续输入 - 整个输入将被删除。

至于函数,您可以调用事件的preventDefault()方法或返回false(您可以在此处阅读方法之间的差异):

    $(document).ready(function () {

        $('#MainContent_LoginUser_Password').keypress(function (e) {
           return noCapsLock(e, "Please turn off Caps Lock");
        });

    });
    function noCapsLock(e, str) {
        var s = String.fromCharCode(e.which);
        if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
            alert(str);
            return false;
        }
        return true;
    }
于 2013-03-18T21:52:39.097 回答