我有以下代码,我想更改
aria-describedby
属性以匹配该 div 中包含的 <h3></h3>
中的文本。我需要通过 .slick-slide
类来识别每个 div。
<div class="cards__card cards__card--1 cards__slide section--light slick-slide slick-current slick-active" data-slick-index="0" aria-hidden="false" tabindex="0" role="tabpanel" id="slick-slide00" aria-describedby="slick-slide-control00">
<div class="cards__slide-wrapper self-center">
<h3 class="section__header cards__header heading heading--h3 ">--- HEADER ---</h3>
<div class="cards__item cards__item--copy">
<p> --- SAMPLE TEXT ---</p>
</div>
<div class="cards__pagination cards__pagination--black">
<p class="copy--disclaimer">1 / 4</p>
</div>
</div>
</div>
我已尝试以下方法但无济于事:
$('div .slick-slide').each(function () {
var h3 = $(this).closest("h3").text();
$(this).attr("aria-describedby", h3);
});
提前谢谢您!
jQuery 的
.closest()
会向上搜索层次结构,而您想要在 .slick-slide
容器内搜索。使用
.find()
代替
$('.slick-slide').each(function () {
var h3 = $(this).find('h3').text().trim();
$(this).attr('aria-describedby', h3);
console.log($(this).attr('aria-describedby'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.slim.min.js"></script>
<div
class="cards__card cards__card--1 cards__slide section--light slick-slide slick-current slick-active"
data-slick-index="0"
aria-hidden="false"
tabindex="0"
role="tabpanel"
id="slick-slide00"
aria-describedby="slick-slide-control00"
>
<div class="cards__slide-wrapper self-center">
<h3 class="section__header cards__header heading heading--h3">
--- HEADER ---
</h3>
<div class="cards__item cards__item--copy">
<p>--- SAMPLE TEXT ---</p>
</div>
<div class="cards__pagination cards__pagination--black">
<p class="copy--disclaimer">1 / 4</p>
</div>
</div>
</div>