简体   繁体   English

如何使用 Javascript 为动态创建的元素添加选项卡索引?

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

I need some help in adding a tabindex to all the elements in a <div> dynamically.我需要一些帮助来动态地将tabindex添加到<div>中的所有元素。 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> .如果我指定一个<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> .我在<div>中显示了标题和描述。 The description is hidden and has a jQuery collapser .描述是隐藏的并且有一个jQuery collapser When I click on the title the description expands.当我点击标题时,描述会展开。 How can I set a tabindex for all the elements?如何为所有元素设置tabindex

Here an example that adds tabindex for all a tags这是a为所有标签添加tabindex的示例

$('#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.您可以对隐藏元素使用相同的方法。

@Sotiris @Sotiris

This might be an update with newer versions of jQuery.这可能是更新版本的 jQuery 的更新。 Use.prop() instead of.attr() to set property values.使用 .prop() 而不是 .attr() 来设置属性值。

$('#Latest-News-Content a').each(function(index) {
    $(this).prop('tabindex', index)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM