Javascript 如何选择";a「;标签在使用jQuery的href中具有特定的文件类型?

Javascript 如何选择";a「;标签在使用jQuery的href中具有特定的文件类型?,javascript,jquery,anchor,href,selector,Javascript,Jquery,Anchor,Href,Selector,我使用以下方法瞄准jQuery中包含各种文件类型的链接: jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=".ods"], a[href$=".txt"], a[href$=".rtf"]').befo

我使用以下方法瞄准jQuery中包含各种文件类型的链接:

jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=".ods"], a[href$=".txt"], a[href$=".rtf"]').before('<span class="glyphicon glyphicon-file"></span> ');

其次,是否有一种方法可以针对文件扩展名的不同情况,例如
Pdf
Pdf
Pdf

您可以使用。在筛选器函数中使用正则表达式检查扩展

$(“a”).filter(函数(){
返回$(this.attr(“href”).match(/\(pdf | doc | docx | ppt | pptx | xls | epub | odp | ods | txt | rtf)$/i);
}).css(“颜色”、“红色”)

不仅仅是使用CSS,还可以创建一个

如果需要支持特殊字符,则必须添加一些转义

我在使用“.attr()”时遇到一些问题。浏览器将返回“TypeError:$(…).attr(…)”,因此经过一些研究后,我发现如果我将“.attr()”替换为“.prop()”,它就解决了这个问题

以下是关于这两方面的一些解释:


谢谢您的功能。

非常好,谢谢。是否使用/\。在regex目标中,只有文件扩展名?@user2726041 No,在javascript中,regex应该设置在
/
之间。还有
\.
匹配点。
jQuery('a[href$=".pdf|.doc|.docx"])
$("a").filter(function(){
   return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
}).before("Some html");
    jQuery.expr[':'].hrefEndsWith = function(
        objNode,
        intStackIndex,
        arrProperties,
        arrNodeStack
        ){
        // The list of arguments gets passed as a string -
        var arrArguments = arrProperties.split(',');
        // Create a jQuery version of this node.
        var jThis = $( objNode );
        // Check to see if this node ends with (we only need to find
        // one of the titles to qualify).
        for (var i = 0 ; i < arrArguments.length ; i++){
            // Check for title equality.
            if (jThis.attr( "href" ).endsWith(arrArguments[i])){
                // We found a href match, return true to
                // indicate that this node should be included
                // in the returned jQuery stack.
                return true ;
            }
        }
        // If we have made it this far, then we found no
        // match. Return false to indicate that this node
        // did not match our selector.
        return false ;
    }

    // Use it
    jQuery("a:hrefEndsWith('.pdf', '.txt', '.xls')");
function getEndsWithSelector(names) {
    return names.map(n => 'a[href$=".'+name+'"]').join();
}

jQuery(getEndsWithSelector('pdf', 'txt', 'xls'))