为了账号安全,请及时绑定邮箱和手机立即绑定

添加 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 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号