为了让自己清楚,让我们从以下示例开始:
function validation(){
$("[name='test']").focus();
// my goal is to focus on the 'name' radio button
//$("[name='test'] return an array with 2 items, but i don't know how to select
//an item, i know that i can use id to skip the problem but this
//won't teach me how to use jQuery
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
name: <input name="test" type="radio" /><br>
age : <input name="test" type="radio" /><br>
<input type="button" onclick="validation()" value = "ok" />
</body>
答案 0 :(得分:0)
首先,通过使用")
$("[name='test']").focus();
接下来,您可以选择具有多个不同伪选择器的特定元素,例如:first,:last,:eq(),nth-child()等等。
$("[name='test']:first").focus();
$("[name='test']:first").focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
name: <input name="test" type="radio" /><br>
age : <input name="test" type="radio" /><br>
<input type="button" onclick="validation()" value = "ok" />
</body>
答案 1 :(得分:0)
设置焦点使用:first
选择器
$("[name='test']:first").focus();
或者,您可以使用.eq(index)
$("[name='test']").eq(0).focus();