JQuery 聚焦并选择 id 输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17748220/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:53:21  来源:igfitidea点击:

JQuery focus and select on id input field

jqueryinputautofocus

提问by secr

DEMO FIDDLE

演示小提琴

<script>
$(document).ready(function ()
{  
     document.getElementById(introdukt).focus()
    document.getElementById(introdukt).select()
});
</script>
<input type="text" size="12" id="introdukt" value="match" style="text-align:center"  />

Does not focus on the field? How to correct this?

不专注领域?如何纠正这个?

回答by Rooster

working fiddle

工作小提琴

$(document).ready(function ()
{  
    $('#introdukt').focus()
    $('#introdukt').select()

    //or if you want to be more efficient and use less characters, chain it
    $('#introdukt').focus().select()

});

your weren't using selectors right. check my fiddle.

你没有正确使用选择器。检查我的小提琴。

also, I changed the id in your fiddle back to introdukt from what you had.

另外,我将您小提琴中的 id 改回了您所拥有的 introdukt。

also, if you're going to use jquery document ready you may as well use the jquery selector instead of the pure js method.

此外,如果您准备使用 jquery 文档,您也可以使用 jquery 选择器而不是纯 js 方法。

回答by Derick

You should chain your method calls since jQuery will only need to look for the element once.

您应该链接您的方法调用,因为 jQuery 只需要查找元素一次。

$(document).ready(function ()
{  
    $('#introdukt').focus().select();
});

回答by Jothi Kannan

check the updated script in jsfiddle

检查jsfiddle 中更新的脚本

HTML:

HTML:

<input type="text" size="12" id="czasow1introdukt" value="match" style="text-align:center"/>

JS:

JS:

$(document).ready(function ()
{  
     document.getElementById('czasow1introdukt').focus()
    document.getElementById('czasow1introdukt').select()
});

回答by George

You need some quotes in there:

你需要一些报价在那里:

document.getElementById('introdukt').focus()
document.getElementById('introdukt').select()

Here's a working Fiddle(Although you've used a different ID on there..?)

这是一个可用的Fiddle(尽管您在那里使用了不同的 ID ..?)

回答by Lucas Willems

You can do it without using js, just with the autofocushtml attribute like that :

您可以在不使用 js 的情况下完成此操作,只需使用这样的autofocushtml 属性即可:

<input autofocus type="text" size="12" id="introdukt" value="match" style="text-align:center"  />

Have a look to this fiddle : http://jsfiddle.net/wrKac/5/

看看这个小提琴:http: //jsfiddle.net/wrKac/5/