首页 > 解决方案 > 自动对焦由 jquery 生成的输入已停止工作

问题描述

我有一个表,其中有一个充当按钮的 img:当我单击它时,该行被克隆并插入到表中。我想确保当我添加新行时它是焦点。最初这段代码有效,创建的最后一行是焦点,但现在它已经停止工作。在写这个问题之前,我尝试了各种解决方案,但没有奏效。当我创建另一行时,我很想将 html autofocus 属性添加到最后一行并将其从上一行中删除,但我认为这不是一个有效的方法。这是该行的html代码:

     <tr>
        <td  class="col-2 align-middle">
            <label for="Server" data-toggle="tooltip" data-placement="top" title="<?php echo $title_Server?>">Server</label>
        </td>
        <td class="col-8 align-middle">
            <input name="Server" class="form-control" type="text" disabled>
        </td>
        <td class="col-2 align-middle my-auto">
            <img class="aggiungiRiga" src="img/add.svg" />
            <img class="modificaRiga" src="img/pencil.svg" />
            <img class="cancellaRiga"  src="img/delete.svg" />
        </td>
    </tr>

这是 jquery/js 管理克隆行的代码。

$('.aggiungiRiga').on('click', function (){
    event.preventDefault();
    $(this).closest("tr").clone().insertAfter('form > table > tbody > tr:last').find('input').attr('autofocus');//.find('input').focus();

    $('form > table > tbody > tr:last td input').prop('disabled', false);
    $('form > table > tbody > tr:last td:last img:nth-child(1)').hide();//css("visibility", "hidden");
    $('form > table > tbody > tr:last td:last img:nth-child(2)').hide();//css("visibility", "hidden");
    $('form > table > tbody > tr:last td:last img:nth-child(3)').attr('class', 'eliminaRiga');
})

标签: javascriptjquery

解决方案


我相信如果元素被禁用则无法聚焦,因此我建议您在 js 中尝试此代码

$('.aggiungiRiga').on('click', function (){
    event.preventDefault();
    var x=$(this).closest("tr").clone().insertAfter('form > table > tbody > tr:last').find('input');//.find('input').focus();
        x.prop('disabled',false)
    x.focus()
    //$('form > table > tbody > tr:last td input').prop('disabled', false);
    $('form > table > tbody > tr:last td:last img:nth-child(1)').hide();//css("visibility", "hidden");
    $('form > table > tbody > tr:last td:last img:nth-child(2)').hide();//css("visibility", "hidden");
    $('form > table > tbody > tr:last td:last img:nth-child(3)').attr('class', 'eliminaRiga');
})

推荐阅读