添加if语句

问题描述 投票:0回答:3

我的代码如下:

$('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/cat1
https://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);
  }
});

但是它不能正常工作。

javascript if-statement
3个回答
1
投票

如果您创建排除域的列表会更好,因此将来添加更多域会更容易。例如这样:

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

1
投票

您也可以做类似的事情:

$('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>

1
投票

通过减小选择器的范围排除了所有不需要的URL

© www.soinside.com 2019 - 2024. All rights reserved.