$(this).focus() 在文本框为空时不起作用

$(this).focus() not working when textbox is empty

本文关键字:不起作用 this focus 文本      更新时间:2023-09-26

我的以下代码在文本框为空时没有设置焦点:

var empty = false;
$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).focus();
        empty = true;
    }
});
if (empty) {
    return false;
}

我们可以把重点放在$(this)元素上吗?我有多个文本框,需要用.Newtxt类进行验证。

试试这个!

$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).focus();
        return false; // To break out of each loop
    }
});

享受!!

使用:

var empty = false;
$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).focus();
        empty = true;
        break; // add this, you have to break cycle, to focus on the first found empty element...
    }
});
if (empty) {
    return false;
}

最后我找到了一个解决方案。试试,让我知道

$('.Newtxt').removeClass('invalid');
$('.Newtxt').each(function () {
    if ($.trim($(this).val()) == "") {
        $(this).addClass('invalid');
        empty = true;
    }
});
if (empty) {
    $(".invalid").eq(0).focus();
    return false;
}