2013-04-08 73 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] 
}); 
相關問題