如何使用 Javascript 为动态创建的元素添加标签索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6699306/
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
How do I add a tab Index for dynamically created elements using Javascript?
提问by Pawan
I need some help in adding a tabindex
to all the elements in a <div>
dynamically. I need to do this for accessibility. If I specify a <div>
element, it should automatically add the tabindex
to all elements in that <div>
.
我需要一些帮助tabindex
来<div>
动态地向 a中的所有元素添加 a 。为了可访问性,我需要这样做。如果我指定了一个<div>
元素,它应该自动将tabindex
加到那个<div>
.
I tried some thing like this:
我试过这样的事情:
$('#Latest-News-Content [tabindex]').each(function () {
$(this).attr( 'tabindex', parseInt( $(this).attr('tabindex') ) + 10 )
});
but it doesn't seem to work. Also, how can I add a tab index for elements which are hidden?
但它似乎不起作用。另外,如何为隐藏的元素添加标签索引?
For example:
例如:
I have a title and description showing in a <div>
. The description is hidden and has a jQuery collapser
. When I click on the title the description expands. How can I set a tabindex
for all the elements?
我有一个标题和描述显示在<div>
. 描述被隐藏并带有jQuery collapser
. 当我单击标题时,描述会展开。如何tabindex
为所有元素设置 a ?
回答by Sotiris
Here an example that adds tabindex
for all a
tags
这是tabindex
为所有a
标签添加的示例
$('#Latest-News-Content a').each(function(index) {
$(this).attr('tabindex', index)
});
Demo: http://jsfiddle.net/azk2n/1
演示:http: //jsfiddle.net/azk2n/1
You can use the same method for hidden elements.
您可以对隐藏元素使用相同的方法。
回答by Ohhh
@Sotiris
@Sotiris
This might be an update with newer versions of jQuery. Use .prop() instead of .attr() to set property values.
这可能是对较新版本 jQuery 的更新。使用 .prop() 而不是 .attr() 来设置属性值。
$('#Latest-News-Content a').each(function(index) {
$(this).prop('tabindex', index)
});