如何通过名称-javascript/jquery 将焦点设置在下拉列表上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19115845/
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 on dropdown by its name -javascript/jquery
提问by manuthalasseril
I have a no of dropdown list as follows
我没有如下下拉列表
<select name="dropname[0]">....</select>
<select name="dropname[1]">....</select>
<select name="dropname[2]">....</select>
<select name="dropname[3]">....</select>....
Now I want to set focus on second drop down list.I tried these
现在我想把重点放在第二个下拉列表上。我试过这些
document.getElementsByName('dropname')[1].focus();
results this error
导致这个错误
TypeError: document.getElementsByName(...)[1] is undefined
Thanks in advance
提前致谢
采纳答案by Johan
Since you tagged your question with jQuery, try something like
既然你用 jQuery 标记了你的问题,试试像
$('select[name^="dropname"]').eq(1).focus();
// $('select[name^="dropname"]') < elements whos name starts with "dropname"
// .eq(1) < select one based on its index
// .focus(); < use jQuery's focus method to set the focus
回答by abcd
Try using jquery focus like
尝试使用 jquery focus 之类的
$("#id2").focus();
回答by Prado
You can use
您可以使用
var i = 0 //or 1,2,3
document.getElementsByName('dropname['+i+']')[0].focus();
hope this will help you
希望能帮到你
回答by Aikansh Mann
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<select name="1">
<option>1</option>
</select>
<select name="2">
<option>2</option>
</select>
<select name="3">
<option>3</option>
</select>
<select name="4">
<option>4</option>
</select>
<select name="5">
<option>5</option>
</select>
<script>
$(document).ready(function(){
i=2;
$('select[name="'+i+'"]').focus();
});
</script>
</body>
</html>
hope this will help you.!
希望能帮到你。!