选择一组CSS选择器中的第一个元素 [英] Select the first element in a set of CSS selectors

查看:1835
本文介绍了选择一组CSS选择器中的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的项目中,我们要为用户建立的约定之一是,当我们打开模式时,我们会自动将打开的模式中可以接受输入的第一个元素作为焦点(输入或下拉菜单.)执行此操作的jQuery代码简单:

On a project I'm working on, one of the conventions we want to set up for our users, is that when we open a modal, we automatically focus the first element of the opened modal that can accept an input (either an input or a dropdown.) The jQuery code for doing that is easy:

$firstElement.focus();

问题在于获取第一个元素.

The problem, is getting that first element.

我们的应用程序模态有时以input开始(例如文本,复选框,日期等),而其他时候以select开始(例如下拉菜单).因此,获得$firstElement有点挑战,因为我需要执行类似以下伪代码的选择:

Our application's modals sometimes start with inputs (e.g. text, checkboxes, dates, etc.), but other times with selects (e.g. dropdowns.) Thus, getting the $firstElement is a bit challenging because I need to perform a selection like the following pseudocode:

(input, select):first

但是,根据我对CSS选择器的了解,我能得到的最接近的是:

However, the closest I've been able to get based on my knowledge of CSS selectors is:

input:first, select:first

问题:使用CSS选择器,我可以通过什么方式选择一组输入和选择中的第一个元素?还是我需要一个更复杂的JavaScript实现来执行我想做的关注焦点优先输入"的事情?

Question: Using CSS selectors, in what way can I select the first element of a set of inputs and selects? Or, do I need a more complex JavaScript implementation to perform the 'focus first input' thing I'm trying to do?

推荐答案

尝试一下:

var $firstElement = $("input, select, textarea").first();


附录:

如果您使用隐藏的inputs,也可以通过以下方法解决此问题:

In case you're using hidden inputs, there's a way around that as well:

var $firstElement = $("input, select, textarea").filter(':visible:first');

这篇关于选择一组CSS选择器中的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆