You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

回车键模拟Tab键功能在表格内失效,如何实现回车跳转下一个输入框

失效原因
  • 原有回车事件采用静态绑定,仅对页面初始化时已存在的输入框生效,后续动态生成的表格输入框未绑定对应事件,无法触发跳转逻辑
  • 动态新增/删除行后没有重新计算所有输入框的tabindex值,且F8新增输入框硬编码了tabindex="0",导致序号顺序混乱,就算事件触发也无法定位到下一个正确的输入框
修复方案

替换原有JS逻辑即可,修正后完整代码如下:

// 公共方法:重置所有非隐藏输入框、选择框的tabindex,保证序号连续
function resetTabIndex() {
    var tabindex = 1;
    $('input,select').each(function() {
        if (this.type != "hidden") {
            $(this).attr("tabindex", tabindex);
            tabindex++;
        }
    });
}

// 回车模拟Tab:改用事件委托,适配动态生成的输入框
$(document).on('keypress', 'input', function(e){
    if(e.which==13){ 
        const nextTabIndex = parseInt($(this).attr("tabindex")) + 1;
        $(`[tabindex="${nextTabIndex}"]`).focus();
        e.preventDefault();
    }
});   

// 页面初始化时根据下拉值生成表格行
$(document).ready(function(){
    samples();
    function samples(){
        $('.appendtablee').html('');
        const rowCount = parseInt($('#asdasdas').val());
        for (var i = 0; i < rowCount; i++) {
            var row = `<tr>
                <td>
                    <label> </label>
                </td>
                <td>
                    <input type="text" name="l[]" class="form" id="legBand1" />        
                     <span class="email_result"></span> 
                </td>
                <td>
                    <input type="text" data-id="wp"  name="W[]" min="1700" max="2200" />        
                </td>
                <td>
                    <input type="text" name="Wi[]"  />        
                </td>
            </tr>`;
            $('.appendtablee').append(row);
        }
        // 生成行后重置tabindex
        resetTabIndex();
    }
})  

// F8快捷键新增行
$(window).keydown(function(e){
    if (e.keyCode == 119) {
        var row = `<tr><td></td><td><input type='text' class='form myInput' name='legBand[]' id='legBand1' /> <span class='email_result'></span></td><td><input type='text' class='myInput' data-id='weight'  name='Weight[]' min='1700' max='2200' /></td><td><input type='text' class='myInput' name='Wingband[]' /></td><td><button type='button' style='float:left;' class='removerow btn btn-danger'>X REMOVE ENTRY</button></td></tr>`;
        $("#wew").append(row);
        // 新增行后重置tabindex
        resetTabIndex();
    }
});

// 删除行逻辑
$("#wew").on("click", ".removerow", function() {
    $(this).closest("tr").remove(); 
    // 删除行后重置tabindex
    resetTabIndex();
});

原有HTML逻辑无需修改。修改后无论初始生成的表格输入框,还是后续F8新增的输入框,按下回车都会自动跳转到下一个输入框,和Tab键效果一致。

内容的提问来源于stack exchange,提问作者Ulquiorra Schiffer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:36:05