Javascript 将焦点设置在特定的选择框上

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

Set focus on specific select box

javascriptjquery

提问by α?jiβ

I have multiple select boxes in the pages. I want to set focus on first element of specific select box. Hereit shows how to set focus on select box. I need to say which one too. I tried below code but it didn't set the focus.

我在页面中有多个选择框。我想将焦点设置在特定选择框的第一个元素上。这里展示了如何在选择框上设置焦点。我也得说是哪一个。我尝试了下面的代码,但它没有设置焦点。

$('#thirdDropBox select:first').focus();

回答by Will

If you want the user to have focus on the first of multiple select's, you can use the following jQuery code:

如果您希望用户专注于多个选择中的第一个,您可以使用以下 jQuery 代码:

If you have an id for the first select, you can directly access that element with the following:

如果您有第一个选择的 id,则可以使用以下命令直接访问该元素:

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

However, if you don't have the id, the following code should work.

但是,如果您没有 id,则以下代码应该可以工作。

Demo: http://jsfiddle.net/biz79/1qo6mxnf/

演示:http: //jsfiddle.net/biz79/1qo6mxnf/

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

On a separate note, if you also want to have a default option selected, you can set that option to "selected" in the HTML:

另外,如果您还想选择一个默认选项,您可以在 HTML 中将该选项设置为“已选择”:

<option value="saab" selected="selected">Saab</option>

回答by PvdBlankevoort

The JQuery selector:

JQuery 选择器:

$('#thirdDropBox select:first')

will select the first "select" html element that is a descendant of an html-element that has an ID-attribute with the value "thirdDropBox".

将选择第一个“选择”html 元素,该元素是具有值为“thirdDropBox”的 ID 属性的 html 元素的后代。

For more information see: http://api.jquery.com/descendant-selector/

有关更多信息,请参阅:http: //api.jquery.com/descendant-selector/

You probably need to remove the '#thirdDropBox"-part from your selector:

您可能需要从选择器中删除“#thirdDropBox”部分:

$('select:first')