将焦点设置为某个类名的下一个元素的输入字段

时间:2016-01-14 20:08:18

标签: javascript jquery

我正在尝试将焦点放在一个元素的第一个输入字段中,该元素的.search-options类位于页面的下一个。

这就是我正在使用的,但它不起作用。

$(document).ready(function() {
    $('.toggle-search-options').on('click', function() {
        $(this).next('.search-options *:input[type!=hidden]:first').focus();
    });
});

2 个答案:

答案 0 :(得分:2)

这与此非常类似:jQuery: Find next element that is not a sibling,但当前元素与您要查找的选择器不匹配。在这种情况下,您只需将其添加到选择中:

// Outside the event handler:
var $elements = $('.search-options *:input[type!=hidden]');

// Inside the event handler:
var $elementsWithCurrentElement = $elements.add(this);
$elementsWithCurrentElement.eq($elementsWithCurrentElement.index(this) + 1).focus();

如果您要查找的元素实际上是兄弟姐妹,请查看Efficient, concise way to find next matching sibling?

答案 1 :(得分:0)

我不明白在“输入”前需要冒号。这对我来说很合适:

$('#test input[type!="hidden"]:first')

但作为替代解决方案,为什么不抓住比赛数组中的第一个呢?

var inputs = $('#test input[type!="hidden"]');
if(inputs.length > 0) { $(inputs[0]).focus(); }