[英]Get child ID and add to parent as ARIA attribute
I have a number of images and captions on a page, set up in <figure><img><figcaption>
groups. 我在页面上有许多图像和标题,它们在
<figure><img><figcaption>
组中进行设置。 I'd like to use JavaScript (or jQuery) to grab the ID of the figcaption
and add an ' aria-labelledby
' attribute to the parent <figure>
. 我想使用JavaScript(或jQuery)来获取
figcaption
的ID,并将' aria-labelledby
'属性添加到父<figure>
。
For example, I have the following (simplified): 例如,我有以下内容(简化):
<figure id="figure1">
<img src="x.jpg">
<figcaption id="caption1">Sample</figcaption>
</figure>
<figure id="figure2">
<img src="y.jpg">
<figcaption id="caption2">Sample</figcaption>
</figure>
How can I loop through each element and add the appropriate 'aria-labelledby' attribute, eg, aria-labelledby="caption1"
? 如何遍历每个元素并添加适当的'aria-labelledby'属性,例如
aria-labelledby="caption1"
?
I tried this but getting an undefined function error: 我尝试了此操作,但收到未定义的函数错误:
$('figure').attr('aria-labelledby', function() {
$(this).find('figcaption').attr('id');
})
Any help appreciated. 任何帮助表示赞赏。
Thanks 谢谢
You need to return
that value, otherwise you're not doing anything with it. 您需要
return
该值,否则将不对其执行任何操作。
$('figure').attr('aria-labelledby', function() {
return $(this).find('figcaption').attr('id');
})
Demo
$('figure').attr('aria-labelledby', function() { return $(this).find('figcaption').attr('id'); })
[aria-labelledby] { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <figure id="figure1"> <img src="x.jpg"> <figcaption id="caption1">Sample</figcaption> </figure> <figure id="figure2"> <img src="y.jpg"> <figcaption id="caption2">Sample</figcaption> </figure>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.