如何为特定的<a>标签设置样式

3

我有很多类似于这样的链接:

<a href="http://www.youtube.com/user/nigahiga">Youtube</a>
<a href="http://pinterest.com/pin/41236152807615600/">Pinterest</a>
<a href="https://www.facebook.com/manchesterunited">Facebook</a>
<a href="http://www.youtube.com/user/RayWilliamJohnson">Youtube</a> 
<a href="http://pinterest.com/pin/24910604158520050/">Pinterest</a>

我该如何为那些链接到Pinterest的超链接添加样式?我尝试了以下方法:
$('a').attr('href').contains('pinterest').css('Styling here');

但它并不起作用。如何实现?

你有在控制台看到错误信息并读懂为什么它不起作用吗?contains()不能用于attr返回的字符串。如果你使用类似于indexof、match或test的东西,你就可以摆脱它。 - epascarello
5个回答

10

您可以使用属性包含选择器:

$('a[href*="pinterest"]').css('color','DeepSkyBlue');

或者更好的方法,只需要纯CSS:

a[href*="pinterest"] {  
    color: DeepSkyBlue;
} 

Fiddle


可以这样写:true,你可以在...css({ color: '#aaf', background: '#444', margin: '20px' })。 - picios

1
  $('a[href*="pinterest"]').css('apply styles');

选择器文档可在http://docs.jquery.com/Selectors找到。

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains

0

您可以使用以下选择器获取所有链接到Pinterest的超链接:

$('a[href^="http://pinterest.com/"]')

该选择器将返回所有以http://pinterest.com/开头的'a'元素。

然后您可以对它们进行样式设置。


0

除了使用属性包含解决方案(虽然不太整洁),您还可以使用filter函数:

$('a').filter(function () {
    return $(this).attr("href").indexOf("pinterest") != -1;
}).css('color', 'red');

这里是一个可运行的例子


0

你应该检查每个a标签的href属性值。

$('a').each(function(){

if($(this).attr('href').contains('pinterest'))

$(this).css(你的样式);

});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接