如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:34:34  来源:igfitidea点击:

How do I add a tab Index for dynamically created elements using Javascript?

javascriptjqueryhtml

提问by Pawan

I need some help in adding a tabindexto 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 tabindexto 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 tabindexfor all the elements?

我有一个标题和描述显示在<div>. 描述被隐藏并带有jQuery collapser. 当我单击标题时,描述会展开。如何tabindex为所有元素设置 a ?

回答by Sotiris

Here an example that adds tabindexfor all atags

这是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)
});