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
Adding tabindex dynamically
提问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 tabindex
numbers.
最好避免n++
设置不同的tabindex
数字。
Instead, try setting tabindex
to 0
:
相反,尝试设置tabindex
为0
:
$(':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 :input
selector basically selects all form controls.
所述:input
选择器基本上选择所有表单控件。
The :visible
selector basically selects all elements that are visible.
所述:visible
选择器选择基本上是可见的所有元素。