jQuery的添加类HREF如果链接中包含特定文本(jQuery add class to href

2019-08-20 07:07发布

我在列表中有我的网站上的一些动态填充链接链接到文件。 是否有可能使用jQuery来看看文件的名称以.PDF结束,并添加一个类中的href或类似的,如果链接文本以.mp3结尾?

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

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

我想检测末端的字母和不同类的链接添加,所以它具有文本Document1.pdf我的类添加链接pdf到锚元素,并用文字Song1.mp3我”链接d将类添加mp3到锚元素。

Answer 1:

使用属性选择:

$('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以获取更多信息。



Answer 2:

给你的所有这些环节都有类.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阵列。



Answer 3:

而不是硬编码的所有类型,你也可以做一个解决方案,将自动为您的所有环节上做到这一点:

var regex = "/\..{3,4}$/";
$('a').each(function() {
    $(this).addClass(regex.match($(this).attr("href"))[0]
});


Answer 4:

$('a[href$=".mp3"]').addClass("mp3");
$('a[href$=".pdf"]').addClass("pdf");


文章来源: jQuery add class to href if link contains specific text