Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

javascript - 一旦出现,如何在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.(我已经看过几个关于bootstrap模态的问题,但没有一个完全像这样,所以我会继续。)

I have a modal that I call onclick like so...(我有一个模态,我打电话就像这样......) $(".modal-link").click(function(event){ $("#modal-content").modal('show'); }); 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.(这工作正常,但是当我显示模态时我想要关注第一个输入元素...在可能的情况下,第一个输入元素的id为#photo_name。) So I tried(所以我试过了) $(".modal-link").click(function(event){ $("#modal-content").modal('show'); $("input#photo_name").focus(); }); But this was to no avail.(但这无济于事。) Lastly, I tried binding to the 'show' event but even so, the input won't focus.(最后,我尝试绑定到'show'事件,但即便如此,输入也不会集中。) 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!(最后只是为了测试,因为我怀疑这是关于js加载顺序,我放入一个setTimeout只是为了看看我是否延迟了一秒,焦点是否有效,是的,它有效!) But this method is obviously crap.(但这种方法显然是废话。) Is there some way to have the same effect as below without using a setTimeout?(有没有办法在不使用setTimeout的情况下获得与下面相同的效果?) $("#modal-content").on('show', function(event){ window.setTimeout(function(){ $(event.currentTarget).find('input#photo_name').first().focus() }, 0500); });   ask by jdkealy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this(试试这个)

Here is the old DEMO :(这是旧的DEMO :) EDIT: (Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)(编辑:(这是一个工作DEMO与Bootstrap 3和jQuery 1.8.3)) $(document).ready(function() { $('#modal-content').modal('show'); $('#modal-content').on('shown', function() { $("#txtname").focus(); }) }); Starting bootstrap 3 need to use shown.bs.modal event:(启动bootstrap 3需要使用shown.bs.modal事件:) $('#modal-content').on('shown.bs.modal', function() { $("#txtname").focus(); })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...