按下回车按钮时聚焦字段



所以我得到了一些帮助,我已经快到了,但我想知道如果我在一个特定的字段中,当我点击回车键时,是否可以有字段焦点。

这是我的代码:http://jsfiddle.net/spadez/xT5X5/2/

当我点击输入一个"已接受"字段时,为了让它集中在"当前"字段上。如果你先添加一些东西,然后点击添加的字段并点击回车键,就会看到这一点。我尝试了这个代码,但运气不佳:

$(".accepted").keyup(function(e) {
    if (e.which == 13) {
        $(".current").focus();
    }
});

此外,我想知道是否有更好的方法将这些"输入"命令添加到我的代码中,因为似乎有更好的方式。

更换

$(".accepted").keyup(function(e) {
    if (e.which == 13) {
        $(".current").focus();
    }
});

带有:

$(document).on("keyup",".accepted",function(e) {
    if (e.which == 13) {
         $(this).closest('.copies').next().find(".current").focus();
    }
});

检查演示

问题是在页面加载时设置keyup事件,然后动态创建文本框-结果是文本框没有绑定到任何事件。

因此,您有两个选项将onClick="添加到文本框中,或者像这样将绑定移动到创建下。

http://jsfiddle.net/xT5X5/4/

            $(html).appendTo(container);
            $(".accepted").keyup(function(e) {
                if (e.which == 13) {
                    $(".current").focus();
                    return false;
                }
            });

您需要将复制的代码部分更改为:

$('.form').on('keyup', '.accepted', function(e) {
    if (e.which == 13) {
        var line = $(this).parent(); // this targets '.line'
        //this targets line's "container", which is '.copy', then find all the .current's in the next node (.line)
        var current = $(line).parent().next().find('.current');
        //as var current returns a list with all the .current's found, even if there's only one, it returns an array of elements in case there were more, so we select the first one from the array
        current = $(current)[0];
        $(current).focus();
    }
});

说明:由于.accepted是一个在文档加载后创建的类,当您绑定keyup函数时,它不存在

你需要使用on(),目标是'.accepted',

我已经分解了如何找到你想要的".current",这样你就可以理解它,但实际上你可以通过几种方式达到它。我用了一个我认为更容易理解的,这里有一个工作小提琴的链接:http://jsfiddle.net/QaHB3/1/

最新更新