一旦出现,如何在 Bootstrap 模式中为特定字段设置焦点 [英] How to set the focus for a particular field in a Bootstrap modal, once it appears
问题描述
我已经看到了几个关于引导模式的问题,但没有一个完全像这样,所以我会继续.
I've seen a couple of questions in regards to bootstrap modals, but none exactly like this, so I'll go ahead.
我有一个模态,我像这样调用 onclick ......
I have a modal that I call onclick like so...
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
});
这很好用,但是当我显示模式时,我想专注于第一个输入元素...在可能的情况下,第一个输入元素的 id 为 #photo_name.
This works fine, but when I show the modal I want to focus on the first input element... In may case the first input element has an id of #photo_name.
所以我尝试了
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
$("input#photo_name").focus();
});
但这无济于事.最后,我尝试绑定到 'show' 事件,但即便如此,输入也不会聚焦.最后只是为了测试,因为我怀疑这是关于 js 加载顺序的,所以我设置了一个 setTimeout 只是为了看看我是否延迟一秒钟,焦点是否有效,是的,它有效!但这种方法显然是废话.有没有什么方法可以在不使用 setTimeout 的情况下获得与下面相同的效果?
But this was to no avail. Lastly, I tried binding to the 'show' event but even so, the input won't focus. Lastly just for testing, as I had a suspiscion this is about the js loading order, I put in a setTimeout just to see if I delay a second, will the focus work, and yes, it works! But this method is obviously crap. Is there some way to have the same effect as below without using a setTimeout?
$("#modal-content").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#photo_name').first().focus()
}, 0500);
});
推荐答案
试试这个
这是旧的DEMO:
(这是一个使用 Bootstrap 3 和 jQuery 1.8 的DEMO.3)
(Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)
$(document).ready(function() {
$('#modal-content').modal('show');
$('#modal-content').on('shown', function() {
$("#txtname").focus();
})
});
启动bootstrap 3需要使用showed.bs.modal事件:
Starting bootstrap 3 need to use shown.bs.modal event:
$('#modal-content').on('shown.bs.modal', function() {
$("#txtname").focus();
})
这篇关于一旦出现,如何在 Bootstrap 模式中为特定字段设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!