简体   繁体   English

在twitter bootstrap模态对话框中关注文本字段

[英]focus for textfield in a twitter bootstrap modal dialog

I need to have the focus for textfield in a twitter bootstrap modal dialog.I have tried the focus() method. 我需要在twitter bootstrap模式对话框中关注textfield。我已经尝试了focus()方法。

DEMO 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: 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>

So, here are a few pointers. 所以,这里有一些指示。 With Bootstrap 3.x there is a function that is triggered by the modal.shown event called thusly, $('#myModal').on('shown.bs.modal', funciton() {...}) which is used to do what your initialize() function is doing. 使用Bootstrap 3.x有一个函数由modal.shown事件触发,因为$('#myModal').on('shown.bs.modal', funciton() {...})这是用来做你的initialize()函数正在做的事情。 To fix the issue with focus() you have to add the following line to your code: 要解决focus()的问题,您必须在代码中添加以下行:

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

The problem is that the input isn't fully ready in the DOM, so you must wait for it to be loaded and ready before you try manipulating it. 问题是DOM中的输入还没有完全准备好,因此在尝试操作之前必须等待它加载并准备就绪。 Here is more documentation on the .ready() function. 这里有关于.ready()函数的更多文档。

Here is the DEMO 这是DEMO

Code Snippet for showing the dialog 用于显示对话框的代码片段

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

not using the ready function,using only modal shown event 不使用ready函数,仅使用模态显示事件

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

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM