【问题标题】:focus for textfield in a twitter bootstrap modal dialogtwitter bootstrap 模态对话框中文本字段的焦点
【发布时间】:2014-05-29 14:34:14
【问题描述】:

我需要在 twitter 引导模式对话框中获得文本字段的焦点。我已经尝试了 focus() 方法。

DEMO

$('#openBtn').click(function(){
    $('#myModal').modal({show:true});
  initialize();
});
function initialize(){

    $('#my').val('');/*empty the textfield for each time
    dialog is called */
   $('#my').focus();//to get focus
}

HTML:

<a href="#" class="btn btn-default" id="openBtn">Open modal</a>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
            <h3>Modal header</h3>
    </div>
    <div class="modal-body">

        <input type="text" id="my" value="">
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Close</button>
    </div>
    </div>
</div>
</div>

【问题讨论】:

  • 可能是重复的 here,尽管我确实尝试使用您的 Bootply 实施该解决方案,但没有帮助。我会继续调查的。

标签: javascript twitter-bootstrap modal-dialog bootstrap-modal


【解决方案1】:

所以,这里有一些建议。在 Bootstrap 3.x 中,有一个由 modal.shown 事件触发的函数,即 $('#myModal').on('shown.bs.modal', funciton() {...}),它用于执行您的 initialize() 函数正在执行的操作。要解决 focus() 的问题,您必须在代码中添加以下行:

$("#my").ready(function() {...})

问题是输入在 DOM 中没有完全准备好,所以你必须等待它被加载并准备好,然后再尝试操作它。 Here 是关于 .ready() 函数的更多文档。

这里是DEMO

【讨论】:

  • 如果您正在寻找这个解决方案,请接受答案:) ps。感谢挑战。我以前从未遇到过这个错误。我一直依赖解决方案mentioned
  • 感谢精心研究的解决方案。我对解决方案进行了即兴创作,并且在准备功能之前首先将文本字段设为空。link
【解决方案2】:

显示对话框的代码片段

$('#openBtn').click(function () {
    $('#myModal').modal({show:true});
    $('#my').val('');//empting the textfield so that dialog does not retain previous state
}); 

不使用ready函数,只使用模态显示事件

$('#myModal').on('shown.bs.modal', function () {
        $("#my").focus();
});

DEMO

【讨论】:

  • 我觉得这只是那些“呃……”时刻之一……我不敢相信我之前没有看到这一点。感谢您事后发布此消息!
猜你喜欢
  • 1970-01-01
  • 2012-03-10
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
相关资源
最近更新 更多