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);
});
添加回答
舉報