如果链接包含特定文本,jQuery将类添加到href [英] jQuery add class to href if link contains specific text
问题描述
我的网站列表中有一些链接到文件的动态填充链接。是否可以使用jQuery查看文件的名称是否以.pdf结尾,如果链接文本以.mp3结尾,则将类添加到href或类似内容?
I have some dynamically populated links in a list on my site that link to files. Is it possible to use jQuery to see if the name of the file ends with .pdf and add a class to the href or similar if the link text ends with .mp3?
例如,我的列表中有以下链接:
For example I have the following links in my list:
- Document1.pdf
- Song1。 mp3
- Song2.m4a
- Document2.doc
- Document1.pdf
- Song1.mp3
- Song2.m4a
- Document2.doc
我想检测结束字母并在链接中添加不同的类,因此对于包含文本Document1.pdf的链接,我将类 pdf
添加到锚元素,以及文本Song1.mp3的链接我将类 mp3
添加到锚元素。
I would like to detect the end letters and add different classes to the links, so to the link which has the text Document1.pdf I'd add the class pdf
to the anchor element, and the link with the text Song1.mp3 I'd add the class mp3
to the anchor element.
推荐答案
使用属性选择器:
$('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 以获取更多信息。
这篇关于如果链接包含特定文本,jQuery将类添加到href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!