亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

添加 if 語句

添加 if 語句

HUH函數 2022-01-13 15:02:53
我的代碼如下所示:$('a').each(function(){  $(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source  + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);});該代碼將一些 UTM 參數添加到站點上的所有鏈接。但現在我想排除一些特定的鏈接:https://www.mysite.or/cat1https://www.mysite.or/cat2所以我想出了這個:$('a').each(function() {  if ("href:contains('https://www.mysite.or/cat1')") {    $(this).attr('href');  } else if ("href:contains('https://www.mysite.or/cat1')") {    $(this).attr('href');  } else {    $(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);  }});但它不能正常工作。
查看完整描述

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>


查看完整回答
反對 回復 2022-01-13
?
蕪湖不蕪

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>


查看完整回答
反對 回復 2022-01-13
?
aluckdog

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);

});


查看完整回答
反對 回復 2022-01-13
  • 3 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號