2013-04-08 9 views
7

У меня есть несколько динамически заполненных ссылок в списке на моем сайте, который ссылается на файлы. Можно ли использовать jQuery, чтобы узнать, заканчивается ли имя файла с .pdf и добавляет класс к href или аналогичному, если текст ссылки заканчивается на .mp3?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

+0

'$ ('а [HREF $ = ". pdf"] '). addClass ("pdf"); ' – Eoin

+0

Отредактировано, спасибо. – Aioros

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] 
});