jQuery добавить класс в href, если ссылка содержит определенный текст
у меня есть некоторые динамически заполненные ссылки в списке на моем сайте, которые ссылаются на файлы. Можно ли использовать jQuery, чтобы увидеть, если имя файла заканчивается .pdf и добавьте класс в href или аналогичный, если текст ссылки заканчивается.mp3?3-->
например, у меня есть следующие ссылки в моем списке:
- Document1.формат PDF
- Song1.mp3
- Song2.конвертировать M4A
- Document2.док!--8-->
Я хотел бы обнаружить конечные буквы и добавьте различные классы к ссылкам, поэтому к ссылке, которая имеет текст Document1.pdf я бы добавил класс pdf к элементу anchor и ссылке с текстом Song1.mp3 я бы добавил класс mp3 к элементу привязки.
4 ответов
используйте селектор атрибутов:
$('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.
Проверьте API для получения дополнительной информации.
учитывая твои все такие ссылки имеют класс .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]);
})
этот код добавит расширение class ко всем таким ссылкам, которые имеют расширение файла в exts массив.
вместо жесткого кодирования всех типов, вы также можете сделать решение, которое будет автоматически сделать это для всех ваших ссылок:
var regex = "/\..{3,4}$/";
$('a').each(function() {
$(this).addClass(regex.match($(this).attr("href"))[0]
});