2009-11-11 33 views
6

如果我有这样一串链接所有链接:添加类链接到某个域与JS(jQuery的)

<a href="foo.com">blah</a> and this <a href="example.com">one</a> and here is another <a href="foo.com"></a>. 

我怎么会一类添加到所有链接到FOO链接.COM?

回答

10

,以确保你得到http://foo.comhttp://bar.foo.com/about,而不是http://bazfoo.com,尝试:

$("a[href*='/foo.com'], a[href*='.foo.com']").addClass('your_class'); 

这里的正则表达式更强的解决方案,这可能是比较慢,你要知道,但检查所访问的开始:

$("a").filter(
    function(){ 
     return $(this).attr('href') 
         .match(/^https?:\/\/([^/]*\.)?foo\.com(\/.*|$)/i); 
    }) 
    .addClass('your_class'); 

这里有一些测试用例:http://jsbin.com/oruhu
(你可以在这里编辑:http://jsbin.com/oruhu/edit)。

1
$("a[href='foo.com']").addClass('your_class') 
0

中平凡: $("a[href='http://foo.com']").addClass('foo'); 但是,假定该URL完全匹配。

3

如果你有联系的像foo的域不同的网页:

<a href="http://foo.com/eggs.html"> 
<a href="http://foo.com/bacon.html"> 

那么你可以使用这样的选择:

$("a[href^=http://foo.com/]").addClass("newClass") 

它会发现,与“http://foo.com/启动所有链接“ 或

$("a[href*=/foo.com/]").addClass("newClass") 

这将找到所有链接包含“/foo.com/”

+1

您的代码在addClass之前缺少'.'。 – Mottie 2009-11-11 07:41:21

+0

固定。谢谢。 – 2009-11-11 14:22:15