[英]How to Set Focus on Input Field using JQuery
給定以下 HTML 結構:
<div class="wrapper">
<div class="top">
<a href="http://example.com" class="link">click here</a>
</div>
<div class="middle">
some text
</div>
<div class="bottom">
<form>
<input type="text" class="post">
<input type="submit">
</form>
</div>
<div>
這將在頁面上重復多次,當用戶單擊 .top div 中的鏈接時, .top
將焦點設置在.bottom
div 中的輸入字段上?
我目前正在使用下面的 JQuery 代碼使.bottom
div 在單擊時成功顯示,但似乎無法弄清楚如何同時將焦點設置在輸入字段上。
$('.link').click(function() {
$(this).parent().siblings('div.bottom').show();
});
謝謝!
試試這個,將焦點設置到第一個輸入字段:
$(this).parent().siblings('div.bottom').find("input.post").focus();
賈斯汀的回答對我不起作用(鉻 18,Firefox 43.0.1)。 jQuery 的.focus()
創建視覺突出顯示,但文本 cursor 不會出現在字段中(jquery 3.1.0)。
受https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/的啟發,我在輸入字段中添加了autofocus屬性,瞧!
function addfield() {
n=$('table tr').length;
$('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
$('input[name="aa"'+n+']').focus();
}
如果輸入恰好在引導模式對話框中,則答案會有所不同。 在顯示后從如何設置焦點復制到引導模式中的第一個文本輸入,這是必需的:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.