繁体   English   中英

将类添加到所有使用js(jquery)链接到特定域的链接

[英]add class to all links that link to a certain domain with 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的所有链接中?

确保您获得http://foo.com,http : //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 )。

如果您具有指向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/”的所有链接

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

琐碎地: $("a[href='http://foo.com']").addClass('foo'); 但这假定URL上完全匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM