单击按钮时如何聚焦下一个文本字段?

Nin*_*jin 2 html javascript jquery

HTML:

<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">

<input type="button" class="mybutton" value="focus next" onclick="focusNext()">
<input type="button" class="mybutton" value="focus prev" onclick="focusPrev()">
Run Code Online (Sandbox Code Playgroud)

JS代码:

//focused is getting last focused textfield
var focused = null;
$(".mytextbox").focus(function(){
    focused = $(this);
});

//focus next
function focusNext(){
    $(".mytextbox").each(

        //checking is this textbox focused
        if($(this)[0] == focused[0]){
              $(this).next().focus(); 
              //or
              $(this).next(".mytextbox").focus(); 
        }
    );
}

//focus prev
function focusPrev(){
    $(".mytextbox").each(

        //checking is this textbox focused
        if($(this)[0] == focused[0]){
              $(this).prev().focus(); 
              //or
              $(this).prev(".mytextbox").focus(); 
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

我认为$(this).next()不工作.. next()功能不在每个???

单击按钮时如何关注下一个或上一个文本字段?帮帮我......谢谢..

Aru*_*hny 5

在你的脚本中你有synatx错误,.each()因为它应该有一个函数作为它的参数.

除此之外,每个循环中都存在逻辑错误,因为您focus()在循环中调用焦点处理程序将被调用并将变换为引用的变量,focus因此下一次迭代也将为真,因此Next按钮将不起作用.

var focused = null;
$(".mytextbox").focus(function () {
    focused = $(this);
});

//focus next
function focusNext() {
    if (focused && focused.length) {
        focused.next('.mytextbox').focus();
    }
}

//focus prev
function focusPrev() {
    if (focused && focused.length) {
        focused.prev('.mytextbox').focus();
    }
}
Run Code Online (Sandbox Code Playgroud)

演示:小提琴