我的网站列表中有一些链接到文件的动态填充链接。是否可以使用jQuery查看文件的名称是否以.pdf结尾,如果链接文本以.mp3结尾,则将类添加到href或类似内容?
例如,我的列表中有以下链接:
我想检测结束字母并为链接添加不同的类,所以对于包含文本Document1.pdf的链接,我将类pdf
添加到锚元素,以及链接文本Song1.mp3我将类mp3
添加到锚元素。
答案 0 :(得分: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 :(得分: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
数组中具有文件扩展名的所有此类链接。
答案 2 :(得分:0)
您可以制作一个解决方案,自动为您的所有链接执行此操作,而不是对所有类型进行硬编码:
var regex = "/\..{3,4}$/";
$('a').each(function() {
$(this).addClass(regex.match($(this).attr("href"))[0]
});
答案 3 :(得分:-1)
$('a[href$=".mp3"]').addClass("mp3");
$('a[href$=".pdf"]').addClass("pdf");