2013-04-08 32 views
7

我在我的网站上链接到文件的列表中有一些动态填充的链接。如果链接文本以.mp3结尾,是否可以使用jQuery来查看文件的名称是否以.pdf结尾并向href或类似链接添加类?如果链接包含特定文本,jQuery将类添加到href中

比如我在我的名单下面的链接:

  • Document1.pdf
  • Song1.mp3
  • Song2.m4a
  • Document2.doc

我会喜欢检测结束字母并添加不同的类到链接,所以到具有文本Document1.pdf的链接我会添加类pdf到锚元素,以及与文本Song1.mp3的链接我会将类mp3添加到锚元素。

回答

35

使用属性选择:

$('a[href$=".mp3"]')... 

选项:

 
    Attribute Contains Prefix Selector [name|="value"] 
    Selects elements that have the specified attribute with a value 
    either equal to a given string or starting with that string followed 
    by a hyphen (-). 

    Attribute Contains Selector [name*="value"] 
    Selects elements that have the specified attribute with a 
    value containing the a given substring. 

    Attribute Contains Word Selector [name~="value"] 
    Selects elements that have the specified attribute with a value 
    containing a given word, delimited by spaces. 

    Attribute Ends With Selector [name$="value"] 
    Selects elements that have the specified attribute with a 
    value ending exactly with a given string. The comparison is case sensitive. 

    Attribute Equals Selector [name="value"] 
    Selects elements that have the specified attribute with a 
    value exactly equal to a certain value. 

    Attribute Not Equal Selector [name!="value"] 
    Select elements that either don’t have the specified attribute, 
    or do have the specified attribute but not with a certain value. 

    Attribute Starts With Selector [name^="value"] 
    Selects elements that have the specified attribute with a 
    value beginning exactly with a given string. 

    Has Attribute Selector [name] 
    Selects elements that have the specified attribute, with any value. 

    Multiple Attribute Selector [name="value"][name2="value2"] 
    Matches elements that match all of the specified attribute filters. 

Check out the API了解更多信息。

-1
$('a[href$=".mp3"]').addClass("mp3"); 
$('a[href$=".pdf"]').addClass("pdf"); 
+0

呃,也许是第二个应该说 – Eoin 2016-09-30 13:01:54

+0

'$('A [HREF $ =“。pdf”]')。addClass(“pdf”);' – Eoin 2016-09-30 13:02:04

+0

编辑,谢谢。 – Aioros 2016-09-30 13:08:06

1

给你所有这些环节都有类.file

var exts = ['pdf','xls']; 
$('a.file').each(function(){ 
    if($(this).attr('href').match(new RegExp('('+exts.join('|')+')'), 'gi')) 
     $(this).addClass($(this).attr('href').match(/\w{3}$/gi)[0]); 
}) 

此代码将在扩展类添加到具有exts阵列的文件扩展名都等环节。

0

而不是硬编码的所有类型,你也可以做一个解决方案,将自动为您的所有环节上做到这一点:

var regex = "/\..{3,4}$/"; 
$('a').each(function() { 
    $(this).addClass(regex.match($(this).attr("href"))[0] 
}); 
相关问题