将类添加到使用js(jquery)链接到特定域的所有链接 [英] add class to all links that link to a certain domain with js (jquery)

查看:74
本文介绍了将类添加到使用js(jquery)链接到特定域的所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一堆这样的链接:

If I have a bunch of links like this:

<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的链接添加一个类?

How would I add a class to all the links that link to foo.com?

推荐答案

以确保您获得 http://foo.com http://bar.foo.com/about ,而不是

to make sure you get http://foo.com, http://bar.foo.com/about, and not http://bazfoo.com, try:

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

这是一个使用正则表达式的更强大的解决方案,请注意,这可能会比较慢,但是请检查域是否在开头:

Here's a stronger solution with regular expressions, this is probably slower, mind you, but checks the domain is on the start:

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

以下是一些测试用例: http://jsbin.com/oruhu
(您可以在此处进行 http://jsbin.com/oruhu/edit ).

Here are some test cases: http://jsbin.com/oruhu
(you can edit it here: http://jsbin.com/oruhu/edit ).

这篇关于将类添加到使用js(jquery)链接到特定域的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆