jQuery 动态添加tabindex

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

Adding tabindex dynamically

jquery

提问by santa

I'd like to add tabindex to all form elements. The form is dymanic and I can't add it to the HTML. I would like to run it as a function. If there are several radiobuttons with the same name, each must have it's own tabindex value. Most of the form elements on page start as INPUT, except SELECT. How do I account for that?

我想将 tabindex 添加到所有表单元素。表单是动态的,我无法将其添加到 HTML 中。我想将它作为函数运行。如果有多个具有相同名称的单选按钮,则每个单选按钮都必须有自己的 tabindex 值。页面上的大多数表单元素都以 INPUT 开头,SELECT 除外。我该如何解释?

I guess I will need to run a loop and add attribute, right?

我想我需要运行一个循环并添加属性,对吗?

var n = 1; 

$('input, select').each(function() {               
    $(this).attr('tabindex', n++);
});

回答by Brandon

Strange question, but yes that's the basic idea:

奇怪的问题,但这是基本思想:

$(":input:not(:hidden)").each(function (i) { $(this).attr('tabindex', i + 1); });

This uses :inputto get everything including buttons and text areas. :not(:hidden)will just exclude the hidden inputs to avoid unnecessary tabs.

这使用:input来获取包括按钮和文本区域在内的所有内容。:not(:hidden)只会排除隐藏的输入以避免不必要的选项卡。

回答by allenski

Might be better to avoid n++to set different tabindexnumbers.

最好避免n++设置不同的tabindex数字。

Instead, try setting tabindexto 0:

相反,尝试设置tabindex0

$(':input:visible').each(function() {               
    $(this).attr('tabindex', '0');
});

tabindex="0"means that the element should be focusable in sequential keyboard navigation, but its order is defined by the document's source order. ~ developer.mozilla.org

tabindex="0"意味着该元素在顺序键盘导航中应该是可聚焦的,但其顺序由文档的源顺序定义。 ~ developer.mozilla.org

The :inputselector basically selects all form controls.

所述:input选择器基本上选择所有表单控件。

The :visibleselector basically selects all elements that are visible.

所述:visible选择器选择基本上是可见的所有元素。