自动将焦点设置在动态加载的输入字段上

Automatically set focus on dynamically loaded input field

使用 jQuery,我试图在 AJAX 调用后在输入字段上执行 .focus(),但到目前为止没有成功。

给出想法的小片段:

$.ajax({
    type: "GET",
    url: url,
    success: function (data) {
        $('#myModal').remove();
        $('body').append(data);
        $('#myModal').modal('show');
    },
    complete: function(){
        $('#input-new-saldo').focus();
    }
});

这是 HTML:(由 AJAX 加载并附加到正文)

        <form id="form-update-saldo">
            <div class="modal-body">
                <div class="form-group">
                    <label class="sr-only" for="input-new-saldo">Saldo (in euro)</label>
                    <div class="input-group">
                        <input type="text" class="form-control input-lg" id="input-new-saldo" name="new_saldo" value="<?php echo $saldo['saldo']; ?>">
                        <div class="input-group-addon">€</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-success" id="submit-update-saldo">Update saldo</button>
            </div>
        </form>

到目前为止我已经尝试过:

  1. 通过其他线程看到了解决相同类型问题的问题,但解决方案似乎对此没有帮助。 (前任。 Javascript focus does not work on dynamically loaded input box jquery focus not working on a page loaded with ajax)
  2. 确保元素在调用过程中存在。确实如此: $('#input-new-saldo');给出正输出。
  3. 确保调用是针对正确的元素。确实如此: $('#input-new-saldo').val('test');更改元素的值。

然而,调用 $('#input-new-saldo').focus();什么都不做,也没有给出任何 JS 错误。

对我来说,在 AJAX 调用我的应用程序之外的某个地方时,焦点似乎以某种方式丢失了,我无法在回调函数中将其窃取回来。这有意义吗?如何解决?

你非常接近。输入元素可以有一个 autofocus 属性 .

所以代替:

$('#input-new-saldo').focus();

尝试:

$('#input-new-saldo').attr('autofocus' , 'true');

希望对您有所帮助

$.ajax({
        type: "GET",
        url: url,
        success: function (data) {
            $('#myModal').remove();
            $('body').append(data);
            $('#myModal').modal('show');
            $('#myModal').on('shown', function() {
                $('#input-new-saldo').focus();
            });
        }
    });

真奇怪,最终找到了直接解决问题的帖子 。

重要的部分是在将事件附加到正文之后将事件绑定到模式,然后再显示它。