使用 jquery 自动将 data-fancybox 属性添加到 img 包装器

Automaticaly add data-fancybox attribute to img wrapper using jquery

我想将 data-fancybox="gallery" 添加到我所有的 <a> 包装器中。

我有这段代码,它实际上用 <a> 包装了所有 <img> 并获取了 src.

$("img").each(function () {
 $(this).wrap($('<a/>', {
    href: $(this).attr('src'),
    selector : '[data-fancybox="images"]',
 }));
});

我想用 data-fancybox="gallery" 替换 selector : '[data-fancybox="images"]',...我不知道该怎么做。

感谢大家的帮助!

可以使用.attr(key, value)方法设置属性值

$("img").each(function () {
    $(this).wrap($('<a/>', {
            href: $(this).attr('src')
        }).attr('data-fancybox', 'gallery'));
});