I started learning jQuery and wanted to make some work on the following structure.
<figure class="blog_image_wrap" style="text-align: center">
<a href="https://ahmcho.com/storage/app/uploads/public/5a6/5d4/672/5a65d467293cd550396758.jpg"><img class="text-center" src="https://ahmcho.com/storage/app/uploads/public/5a6/5d4/672/5a65d467293cd550396758.jpg" style="width:50%;"></a>
<figcaption class="blog_image_wrap">
Gary Oldman
</figcaption>
</figure>
There are multiple <figure>
tags in one page and I want to extract the text of corresponding <figcaption>
and pass it as a value of data-caption
attribute for <a>
tag. For all '' elements inside '' elements.
I have the following code but it passes all text values of <figcaption>
texts as one for all <a>
elements :
$(document).ready(function()
{
$('figure').each(function()
{
$("figure>a").attr('data-caption', $("figure").find('figcaption').text());
});
$("figure>a").attr("data-fancybox" , "test");
});
I would appreciate if someone would point me what am I doing wrong.
答案 0 :(得分:0)
在this
的每次迭代中尝试使用each()
定位当前元素。然后从该元素中找到特定的a
以设置属性。请尝试以下方式:
$(document).ready(function() {
$('figure').each(function() {
$(this).find('a').attr('data-caption', $(this).find('figcaption').text());
$(this).find('a').attr("data-fancybox" , "test");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure class="blog_image_wrap" style="text-align: center">
<a href="https://ahmcho.com/storage/app/uploads/public/5a6/5d4/672/5a65d467293cd550396758.jpg"><img class="text-center" src="https://ahmcho.com/storage/app/uploads/public/5a6/5d4/672/5a65d467293cd550396758.jpg" style="width:50%;"></a>
<figcaption class="blog_image_wrap">
Gary Oldman
</figcaption>
</figure>
答案 1 :(得分:0)
由于您遍历图,因此需要在当前迭代中找到a
和figcaption
。要查找当前的图形对象,可以使用$(this)
。因此,要找到a
和figcatption
,您可以使用以下代码:
$(document).ready(function()
{
$('figure').each(function()
{
$(this).find("a").attr('data-caption', $(this).find('figcaption').text());
});
});