如果链接包含特定文本,jQuery将类添加到href

Sam*_*row 7 javascript jquery append href

我的网站列表中有一些动态填充的链接链接到文件.是否可以使用jQuery查看文件的名称是否以.pdf结尾,如果链接文本以.mp3结尾,则将类添加到href或类似内容?

例如,我的列表中有以下链接:

  • Document1.pdf
  • Song1.mp3
  • Song2.m4a
  • Document2.doc

我想检测结束字母并为链接添加不同的类,所以对于具有文本Document1.pdf的链接我将类添加pdf到锚元素,以及带有文本Song1.mp3的链接我会将类添加mp3到锚元素.

Jam*_*ill 35

使用属性选择器:

$('a[href$=".mp3"]')...
Run Code Online (Sandbox Code Playgroud)

选项:

    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以获取更多信息.