页面中会多次重复的公共组件如何添加aria-labelledby="*"属性?

How to add aria-labelledby="*" attributes to common components that will be repeated multiple times in a page?

我有一个将在给定页面中多次使用的通用下拉组件:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="I cannot add a static ID here since this will be repeated multiple times in a page" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="How to reference the above button here?">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Separated link</a></li>
  </ul>
</div>

我不想为我的按钮添加 ID,因为它会在页面中重复多次。 有没有其他方法可以在此处添加 aria-labelledby 属性而不动态生成 id?

aria-labelledby, from MDN:

contains the element IDs of labels in objects such as input elements, widgets, and groups

如果您想使用 labelledby,您需要有 ID。但是,您可以为不同的按钮使用 不同的 ID,并让项目使用相关 ID 作为其 labelledby 属性的一部分。

如果您使用的是内容管理系统,您应该能够编写一个循环,生成一个带有数字的 ID,使每个按钮与不同的 ID 相关联,并重新使用该 ID 作为labelledby

labelledby 的值不需要有意义;这是一个告诉辅助技术的钩子 "Thing A is labelled by the thing with this ID"。