如何在刚刚出现的元素上使用 jQuery 设置焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9327857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set focus using jQuery on an element that has just appeared
提问by DaFoot
I have a document ready block as follows:
我有一个文档就绪块,如下所示:
$(document).ready(function () {
$('#addTagLink').click(function () {
$('#addTagField').show();
$('#addTagField').val("");
$('#addTagField').focus();
});
});
The addTagField
is a regular text input that has display:none set by css on page load.
这addTagField
是一个常规文本输入,在页面加载时由 css 设置 display:none。
When a user clicks on the addTagLink
element the input field is shown correctly but focus doesn't get set to the field as intended.
当用户单击addTagLink
元素时,输入字段会正确显示,但焦点未按预期设置到该字段。
I figured it must be something to do with the display:none / show() functionality, so changed the $('#addTagField').focus();
to another field $('#name').focus();
which worked perfectly.
我认为这一定与 display:none / show() 功能有关,因此将其更改$('#addTagField').focus();
为另一个$('#name').focus();
完美运行的字段。
Can anyone suggest firstly why I see this issue and secondly, how to fix it?
任何人都可以首先建议为什么我会看到这个问题,其次,如何解决它?
回答by DaFoot
Turns out it was a problem with my element IDs. Oops.
原来是我的元素 ID 有问题。哎呀。
回答by Mohammad Ayoub Khan
// Variable to store element
var btn = document.querySelector( ".btn-primary");
// Click Event
$(btn).click(function() {
// Jquery to define which element will get focus
$(".form-control").focus();
});