我加载了一个动态 bootstrap 模式,它包含很少的文本输入.我面临的问题是,我希望光标集中在这个模式中的第一个输入上,而这在默认情况下不会发生

$('#modalContainer').on('show', function () {
   $('input:text:visible:first').focus();
});

但现在它只关注输入中的一小部分,然后自动消失,为什么会发生这种情况,以及如何解决?

推荐答案

@scumah has the answer for you: Twitter bootstrap - Focus on textarea inside a modal on click

对于Bootstrap 2

modal.$el.on('shown', function () {
$('input:text:visible:first', this).focus();
});  

更新:适用于Bootstrap 3

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

========== Update ======

In response to a question, you can use this with multiple modals on the same page if you specify different data-targets, rename your modals IDs to match and update the IDs of the form input fields, and finally update your JS to match these new IDs:
see http://jsfiddle.net/panchroma/owtqhpzr/5/

HTML

...
<button ... data-target="#myModal1"> ... </button> 
... 
<!-- Modal 1 -->
<div class="modal fade" id="myModal1" ...>
... 

<div class="modal-body"> <textarea id="textareaID1" ...></textarea></div>

JS

$('#myModal1').on('shown.bs.modal', function() {
  $('#textareaID1').focus();
})

Jquery相关问答推荐

bootstrap - Select Select 器不能在下拉菜单中 Select

jQueryUI 模态对话框不显示关闭按钮 (x)

如何从 jQuery 转到 React.js?

提醒未保存的表单更改

如何使用 jQuery 将表格的一行滚动到视图 (element.scrollintoView) 中?

使用 JQuery 清除下拉列表

jQuery 中的 $this 与 $(this)

JavaScript 吸管(告诉鼠标光标下像素的 colored颜色 )

jQuery getJSON 将结果保存到变量中

如何获取 onclick 调用对象?

如何通过 DOM 容器访问 Highcharts 图表?

DataTables:无法读取未定义的属性长度

jquery在加载时获取iframe内容的高度

如何使用 Twitter Bootstrap 自动关闭alert

如何获得元素的正确偏移量? - jQuery

$(document).ready(function(){});页面底部的 vs 脚本

如何隐藏 Twitter Bootstrap 下拉菜单

将多个 JavaScript 文件合并为一个 JS 文件

你如何记录jQuery中一个元素触发的所有事件?

为什么我应该创建异步 WebAPI 操作而不是同步操作?