[英]add class to all links that link to a certain domain with 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>.
How would I add a class to all the links that link to foo.com? 如何将一个类添加到链接到foo.com的所有链接中?
to make sure you get http://foo.com , http://bar.foo.com/about , and not http://bazfoo.com , try: 确保您获得http://foo.com,http : //bar.foo.com/about而不是http://bazfoo.com ,请尝试:
$("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');
Here are some test cases: http://jsbin.com/oruhu 以下是一些测试用例: http : //jsbin.com/oruhu
(you can edit it here: http://jsbin.com/oruhu/edit ). (您可以在此处进行编辑: http : //jsbin.com/oruhu/edit )。
If you have links to distinct pages on the foo domain like: 如果您具有指向foo域上不同页面的链接,例如:
<a href="http://foo.com/eggs.html">
<a href="http://foo.com/bacon.html">
then you can use a selector like this: 那么您可以使用如下选择器:
$("a[href^=http://foo.com/]").addClass("newClass")
which will find all links that start with " http://foo.com/ " or 它将找到所有以“ http://foo.com/ ”开头的链接或
$("a[href*=/foo.com/]").addClass("newClass")
which will find all links that contain "/foo.com/" 它将查找包含“ /foo.com/”的所有链接
$("a[href='foo.com']").addClass('your_class')
Trivially: $("a[href='http://foo.com']").addClass('foo');
琐碎地:
$("a[href='http://foo.com']").addClass('foo');
But that assumes an exact match on the URL. 但这假定URL上完全匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.