Javascript 使用js(jquery)将类添加到链接到特定域的所有链接
如果我有一堆这样的链接:Javascript 使用js(jquery)将类添加到链接到特定域的所有链接,javascript,jquery,Javascript,Jquery,如果我有一堆这样的链接: <a href="foo.com">blah</a> and this <a href="example.com">one</a> and here is another <a href="foo.com"></a>. $("a[href^=http://foo.com/]").addClass("newClass") 这是另一个。 如何将类添加到所有链接到foo.com的链接中?很简单: $
<a href="foo.com">blah</a> and this <a href="example.com">one</a> and here is another <a href="foo.com"></a>.
$("a[href^=http://foo.com/]").addClass("newClass")
这是另一个。
如何将类添加到所有链接到foo.com的链接中?很简单:
$("a[href='foo.com']").addClass('your_class')
$(“a[href=”http://foo.comaddClass('foo')代码>
但这需要与URL完全匹配。要确保您得到的是,而不是,请尝试:
这里有一个更强大的正则表达式解决方案,请注意,这可能会更慢,但检查域是否处于启动状态:
$("a").filter(
function(){
return $(this).attr('href')
.match(/^https?:\/\/([^/]*\.)?foo\.com(\/.*|$)/i);
})
.addClass('your_class');
以下是一些测试用例:
(您可以在此处编辑:) 如果您有指向foo域上不同页面的链接,如:
<a href="http://foo.com/eggs.html">
<a href="http://foo.com/bacon.html">
将查找以“”开头的所有链接
或
这将找到所有包含“/foo.com/”的链接。这非常理想!我可能会将*
选择器替换为+
,以使表达式更有效,并且不匹配以下内容http://.foo.com
$("a[href^=http://foo.com/]").addClass("newClass")
$("a[href*=/foo.com/]").addClass("newClass")