如何使用 jQuery select "a" 标签在 href 中具有特定的文件类型?

How to select "a" tag has specific file type in href using jQuery?

我的目标链接包含 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> ');

首先,有没有办法减少重复?例如

jQuery('a[href$=".pdf|.doc|.docx"])

其次,有没有办法针对文件扩展名的不同情况,例如PdfPDFpdf?

您可以使用 .filter(). In filter function check extension using regex in String.prototype.match() 过滤所选元素。

$("a").filter(function(){
   return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
}).before("Some html");

$("a").filter(function(){
  return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
}).css("color", "red")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="file.pdf">pdf</a>
<a href="file.doc">doc</a>
<a href="file.html">html</a>
<a href="file.docx">docx</a>
<a href="file.ppt">ppt</a>
<a href="file.php">php</a>
<a href="file.slxs">slxs</a>
<a href="file.txt">txt</a>

请注意 i 正则表达式匹配末尾的标志不区分大小写。

不是简单地使用 CSS,而是可以创建一个 custom selector

    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')");

或者,如果您不需要所有这些,您可以只编写一个 JS 函数来创建您的选择器。

function getEndsWithSelector(names) {
    return names.map(n => 'a[href$=".'+name+'"]').join();
}

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

如果你需要支持特殊字符,你将不得不添加一些转义

我在使用“.attr()”时遇到了一些问题。浏览器会 return "TypeError: $(…).attr(…)",所以经过一些研究,我发现如果我将“.attr()”替换为“.prop()”,问题就解决了。

以下是关于两者的一些解释:.prop() vs .attr()

感谢功能。