如果我有一堆这样的链接:
<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)。
关于javascript - 使用 js (jquery) 将类添加到链接到某个域的所有链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1713222/