从<figcaption>标签中覆盖/插入新的alt标签

4
我有一段jQuery代码见下方,它使用href标签将我的图片进行包裹,以便在lightbox中使用。
我需要调整alt标签中显示的内容,这些内容需要从用户在ckeditor的标题框内输入的内容生成(该输入将在每个图像下生成figcaption标签)。我需要能够将这些数据插入到空的alt = ""中,并且可以覆盖当前在alt标签中的任何内容。
目前输出的HTML为:
<figure class="image">
    <a data-imagelightbox="f" href="/ckfinder/userfiles/files/Screenshot_South-Downs-Lines-RSC_51_23330-1_22091_10-00-48.jpg">
        <img width="1600" height="900" src="/ckfinder/userfiles/files/Screenshot_South-Downs-Lines-RSC_51_23330-1_22091_10-00-48.jpg" alt="Caption 1"></img>
    </a>
    <figcaption>
        Caption
    </figcaption>
</figure>

我目前的脚本如下:

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

感谢您的帮助。

这是函数运行前还是后的HTML? - GreyRoofPigeon
HTML是在jQuery运行后生成的,目前只将图像包装在href中,但当前不会更改alt标签,这就是我想要实现的。谢谢。 - Rob88991
1个回答

1

如果我理解正确,你想要更改图像的alt属性。那么这应该可以工作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接