通过单击按钮关注下一个元素

Focus on next element by clicking the button

我的目的是在按钮触发 mouseup 事件时将焦点移动到下一个输入元素,这是脚本:

var cleared = false;
$(document).ready(function(){

    //focus on first element
    var focused = null;
    $(".inp").focus(function () {
        focused = $(this);
    }).first().focus();

   //when mousedown, set value 4
    $("#btn").mousedown(function(e) {
        focused.val("4");  
    }).mouseup(function(e) {

        //when mouseup, change bg color
        focused.css("background-color","yellow");

        //and focus on next element
        if (focused && focused.length) {
            focused.next(".inp").focus();
        }       
    });
});

这是我的 html 元素:

    <table>     
        <tr>
            <td>ABC</td>
            <td><input class="inp"/></td>
            <td><input class="inp"/></td>
            <td><input class="inp"/></td>
        </tr>
    </table>
<button id="btn">4</button>Good

我的问题是焦点永远不会设置下一个,我该如何解决?

试试这个以专注于下一个元素

 $(this).trigger("keydown", [9]);

替换代码中的以下内容

   if (focused && focused.length) {
        focused.next(".inp").focus();
    }

Working fiddle

next() :Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

你没有 'immediately following sibling' 和 class inp,所以你必须向上移动一次到父 td 然后移动到下一个 td 使用 next() 函数,然后在这个 td 中找到 class inp 并执行焦点。

只需替换:

focused.next(".inp").focus();

作者:

focused.parent().next().find(".inp").focus();

完整的 JS :

var cleared = false;
$(document).ready(function(){

    //focus on first element
    var focused = null;
    $(".inp").focus(function () {
        focused = $(this);
    }).first().focus();

   //when mousedown, set value 4
    $("#btn").mousedown(function(e) {
        focused.val("4");  
    }).mouseup(function(e) {

        //when mouseup, change bg color
        focused.css("background-color","yellow");

        //and focus on next element
        if (focused && focused.length) {
            focused.parent().next().find(".inp").focus();
        }       
    });
});

希望这对您有所帮助。