简体   繁体   English

使用jQuery查找特定的文件扩展名并添加属性

[英]Use jQuery to look for specific file extensions and add attribute

I'm wondering if someone can help. 我想知道是否有人可以提供帮助。 I'm trying to use jQuery to look for specific file extensions in an href and if it finds it add an attribute "data-lightbox". 我正在尝试使用jQuery在href中查找特定的文件扩展名,如果找到它,则添加一个属性“ data-lightbox”。 This is what I have thus far: 到目前为止,这是我所拥有的:

$(document).ready(function() {
    var valid_extensions = /(\.jpg|\.jpeg|\.gif\.png|)$/i;   
    $(".banner ul li.dfwp-item a").each(function() {
        filename = $(this).attr( "href" );
    });
    $(".banner ul li.dfwp-item a").each(function() {
        if(valid_extensions.test(filename))
        { 
            $(this).attr( "data-lightbox", "BannerLightbox" );
            alert('Woo hoo');
        }
        else
        {
            alert('Invalid File');
        }
    });
});

Thanks! 谢谢!

Here is your corrected code: 这是您的更正代码:

$(document).ready(function() {
    var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.png)$/i;   
    $(".banner ul li.dfwp-item a").each(function() {
        filename = $(this).attr("href");
        if(valid_extensions.test(filename))
        { 
            $(this).data("lightbox", "BannerLightbox");
            alert('Woo hoo');
        }
        else
        {
            alert('Invalid File');
        }
    });
});

You need to drop the second .each() and move the pipe ( | ) in your pattern. 您需要删除第二个.each()并在模式中移动管道( | )。 You can also use .data() instead of .attr() . 您也可以使用.data()代替.attr()

看起来您缺少.gif和.png之间的管道,但是之后有一个多余的管道可以匹配任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM