当文本框为空时,$(this).focus()无效

时间:2015-06-11 11:47:29

标签: javascript jquery

以下代码在文本框为空时不设置焦点:

var empty = false;

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

if (empty) {
    return false;
}

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

3 个答案:

答案 0 :(得分:0)

使用:

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;
}

答案 1 :(得分:0)

试试这个!

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

享受!!

答案 2 :(得分:0)

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

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

if (empty) {
    $(".invalid").eq(0).focus();
    return false;
}