JQuery onclick 函数聚焦输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7285197/
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
JQuery onclick function to focus input
提问by Robin I Knight
I want a JQuery function that means if the user clicks on some text on the page it focuses an input.
我想要一个 JQuery 函数,这意味着如果用户单击页面上的某些文本,它会聚焦输入。
$(document).ready(function(){
$('#header.search span').click(function(){
$('#header.search input').focus();
});
});
That did not do anything. On Firebug nothing is registered.
那没有做任何事情。在 Firebug 上没有注册任何内容。
Any ideas?
有任何想法吗?
Marvellous
奇妙
回答by Henry
http://jsfiddle.net/HenryGarle/LXngq/
http://jsfiddle.net/HenryGarle/LXngq/
<span>
<br>
Span
<br>
<input id="InputToFocus" type="text">
</span>
$('span').click(function(){
$('#InputToFocus').focus();
});
Seems to be working fine, It is probably a problem with your selectors. Could you post the structure of your HTML surrounding the input?
似乎工作正常,这可能是您的选择器有问题。您可以发布围绕输入的 HTML 结构吗?
回答by ShankarSangoli
If you have id
to the input element then you dont need javascript to do this. You can use for
attribute with a label
tag pointing to the input element id. Try this
如果您必须id
输入元素,那么您不需要 javascript 来执行此操作。您可以使用for
带有label
指向输入元素 id的标签的属性。尝试这个
Working demo
工作演示
<label for="input1">Name</label>
<input id="input1" type="text" />
If you click on Name text the focus will be set into the input field.
如果您单击名称文本,焦点将设置在输入字段中。
回答by Gurpreet Singh
$( "input" ).focus(function() {
$( this ).next( "span" ).css( "display", "inline" ).fadeOut( 1000 );
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text"> <span>focus fire</span></p>
<p><input type="password"> <span>focus fire</span></p>
回答by Obi
I think $('#header.search input') returns a bunch of INPUTs, not just one, so JQuery may not know which one to focus. You'll need to decide which one to focus.
我认为 $('#header.search input') 返回一堆 INPUT,而不仅仅是一个,因此 JQuery 可能不知道要关注哪个。您需要决定关注哪一个。