如何使用jquery调用<figcaption>并插入<a> tag

时间:2015-07-09 15:40:01

标签: jquery html5

I'm trying to call the content held within the element and insert it into the tag so that it can be used as the caption on the lightbox.

The html looks like:

<figure class="image">
    <img alt="sadasdasd" src="http://i.telegraph.co.uk/multimedia/archive/02580/japan-train_2580841k.jpg" />
    <figcaption>adsasdsa</figcaption>
</figure>

The jQuery I am using is below:

$('#article-copy img').each( function() {
    var $img = $(this),
    caption = $("figcaption"),
    href = $img.attr('src');
    $img.wrap('<a href="' + href + '" class="fresco" data-fresco-group="unique_name" data-fresco-caption="' + caption + '"></a>');
});

Thank you for any help.

1 个答案:

答案 0 :(得分:0)

根据你的说法,你点击它时会得到img元素,所以你得到了href来使用它。但是你无法触及figcaption因为它不在img元素上。这是兄弟元素。我们可以使用next

来实现
$img.next('figcaption').text();

但您可能更喜欢使用其他功能,例如find。您可以在jQuery tree traversal api文档中查看您的选项。使用next()可以得到:

$('#article-copy img').each( function() {
    var $img = $(this),
    caption = $img.next('figcaption').text(),
    href = $img.attr('src');
    $img.wrap('<a href="' + href + '" class="fresco" data-fresco-group="unique_name" data-fresco-caption="' + caption + '"></a>');
});