使用is(':last')来检查最后一个元素

时间:2011-07-09 10:06:57

标签: javascript jquery

我有一个输入元素列表。我想将keyup事件处理程序绑定到它们,这样每当用户点击 Enter 时,他就会转到下一个字段。但是如果输入是最后一个输入,那么我想触发按钮的click事件,以便用户进入另一个级别。我的代码是这样的:

$('.loginBody input:visible').keyup(function (e) {
    if (e.keyCode == 13) {
        if ($(this).is(':last')) {
            $('#next').click();
        }
        else {
            $(this).closest('input').focus();
        }
    }
});

然而,似乎is(':last')不起作用。怎么了?

4 个答案:

答案 0 :(得分:5)

:last返回集合的最后一个元素,而$(this)只是一个元素集合。

请尝试使用:last-child选择器,这将检查您的<input>是否真的是该组中的最后一个。

或者,如果您的字段不在同一个父级中,则反转您的测试意义:

if ($('input').filter(':last').is(this)) {
    // this is the last input
}

注意:http://api.jquery.com/last-selector/每个建议使用.filter(':last')而不是input:last

答案 1 :(得分:2)

更新:您可以创建两个不同的绑定:

$('.loginBody input:last').keyup(function (e) {
    if (e.which == 13) {
             $("#result").html("last one");
        }
    });

$('.loginBody input').not(":last").keyup(function (e) {
    if (e.which == 13) {
             $("#result").html("not last one");
        }
});

以下是一个工作示例:http://jsfiddle.net/6gYXk/1/

答案 2 :(得分:1)

您是否尝试过 is(':last-child')伪类?

:last-child表示“如果此元素是其父元素的最后一个子元素”。请注意,只有元素节点(HTML标记)计数,这些伪类忽略文本节点。

修改 还要关注最近的兄弟元素使用:

 $(e.target).next('input').focus();

所以完整的代码可以是:

$('.loginBody input:visible').keyup(function (e) {
    if (e.keyCode == 13) {
        if ($(this).is(':last-child')) {
            $('#next').click();
        } else {
             $(e.target).next('input').focus();
        }
    }
});

我准备了一个例子:http://jsfiddle.net/HhvUF/

答案 3 :(得分:0)

最好的解决方案可能是使用nextAll查看是否有任何后续兄弟元素:

if ($(this).nextAll().length) {
    $(this).closest('input').focus();
} else {
    $('#next').click();
}

请注意,我已将if转过来,以便于阅读。

如果您只需检查input元素,则可以提供选择器:

if ($(this).nextAll('input').length) {