3 回答

TA贡献1829条经验 获得超6个赞
通过缩小选择器的范围,排除所有不需要的 url
$('a:not([href$="cat1"]):not([href$="cat2"])').each(function() {
$(this).attr('href', ...);
});
$=表示以 结尾的属性
$('a:not([href$="cat1"]):not([href$="cat2"])').each(function() {
$(this).html('changed')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="http://somelink/cat0">untouched</a>
<a href="http://somelink/cat1">untouched</a>
<a href="http://somelink/cat2">untouched</a>
<a href="http://somelink/cat3">untouched</a>
<a href="http://somelink/cat4">untouched</a>

TA贡献1796条经验 获得超7个赞
您还可以执行以下操作:
$('a:not([href^="https://www.mysite.or/cat"])')
这只会选择<a>不包含以开头的 href 的标签https://www.mysite.or/cat
$('a:not([href^="https://www.mysite.or/cat"])').each(function() {
$(this).addClass('found');
});
.found {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">some</a>
<a href="https://www.mysite.or/cat2">xxx1</a>
<a href="https://www.mysite.or/cat1">xxx1</a>

TA贡献1847条经验 获得超7个赞
如果您创建一个排除域列表会更好,这样将来添加更多域会更容易。例如像这样:
var exclude = [
"https://www.mysite.or/cat1",
"https://www.anysite.com"
]
$('a').each(function() {
var href = $(this).attr('href');
if (exclude.indexOf(href) === -1) {
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
}
});
正如@caramba 在评论中指出的那样,如果您关心性能(即您有数千个a要迭代的域或数十个排除域),上述解决方案并不是最快的。另一种可能的解决方案(同时保持代码易于维护)是构建一个选择器并将其传递给 jQuery:
var exclude = [
"https://www.mysite.or/cat1",
"https://www.anysite.com"
]
var nots = exclude.map(function(domain) {
return ':not([href="' + domain + '"])';
}).join('');
$('a' + nots).each(function() {
var href = $(this).attr('href');
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
添加回答
举报