0

我有一个文本框,当我单击它(焦点)时会突出显示红色。如果我在其中输入任何内容,它会突出显示为灰色。但是,当我在其中输入内容并再次删除其中的所有数据时,它不会突出显示为红色。请帮帮我。这是我用来突出显示它的红色和灰色的一段代码:

$("#fname").bind('focus', function (e) {
    if ((document.getElementById("fname").value).length == 0) {
        document.getElementById("fname_error").style.display = "inline";
        $("#fname").attr('style', 'border: 1px solid #8C0005 !important;');

        return false;
    }
    else {
        document.getElementById("fname_error").style.display = "none";
    }
    return true;
});

$("#fname").keypress(function (e) {
    var iKeyCode = (e.which) ? e.which : e.keyCode


    if ((iKeyCode > 64 && iKeyCode < 91) || (iKeyCode > 96 && iKeyCode <      123) || iKeyCode==8 || iKeyCode == 9 ) {

                document.getElementById("fname_error").style.display = "none";
                $("#fname").attr('style', 'border: 1px solid #cccccc !important;');
                return true;

    }
    else {
            document.getElementById("fname_error").style.display = "inline";
            return false;
        }

});
4

1 回答 1

0

那是因为您在focus事件处理程序中设置了红色边框,如果元素已经获得焦点,则无法触发此事件。

尝试将此代码移动到keyup处理程序。

于 2016-07-05T07:01:49.717 回答