查找特定的 URL 基于 link 并通过 jquery 在 rel 属性中添加额外的值到完整的网站

Find Specific URL based link and add extra value in rel attributes into full website via jquery

我想在所有链接为 rel='nofollow' 和 href='example.com' 的属性中添加额外的值。有关详细信息,我在下面附上我的代码。

我的预期输出:

<a target="_blank" rel="nofollow sponsored" class="" href="https://amzn.to/tes" style="width: 100%;">Aff Link</a>
<a target="_blank" rel="follow" href="example.com">Follow</a>

我的代码如下:

var test = jQuery('a').attr('href').split('/')[2];

if (test == 'amzn.to') {
  jQuery('a').attr('rel', 'nofollow sponsored');
  console.log(test);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Rel Attribute</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
  <a href="example.com">Example link</a> <br>
  <a target="_blank" rel="nofollow" class="" href="https://amzn.to/tessdft" style="width: 100%;">
        Link 1
    </a> <br>
  <a target="_blank" rel="nofollow" class="" href="https://amzn.to/testws" style="width: 100%;">
        Link 2
    </a> <br>
  <a target="_blank" rel="nofollow" class="" href="https://amzn.to/testee" style="width: 100%;">
        Link
    </a> <br>

</body>

</html>

你的线路

jQuery('a').attr('href')

只会 return 第一个 a 的 href - 你需要循环每个 a:

console.log("before: " + $("a[rel*=sponsored]").length)

$("a").each(function() {
  var test = $(this).attr('href').split('/')[2];

  if (test == 'amzn.to') {
    $(this).attr('rel', 'nofollow sponsored');
    console.log(test);
  }
});

console.log("after: " + $("a[rel*=sponsored]").length)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<a href="example.com">Example link</a> <br>
<a target="_blank" rel="nofollow" href="https://amzn.to/tessdft">Link 1</a><br>
<a target="_blank" rel="nofollow" href="https://amzn.to/testws">Link 2</a><br>
<a target="_blank" rel="nofollow" href="https://amzn.to/testee">Link3</a><br>

还有一个 overload for .attr 允许你传递一个函数

console.log("before: " + $("a[rel*=sponsored]").length)

$("a").attr("rel", function() {
  var test = $(this).attr('href').split('/')[2];
  if (test == 'amzn.to') {
    return 'nofollow sponsored';
  }
});

console.log("after: " + $("a[rel*=sponsored]").length)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<a href="example.com">Example link</a> <br>
<a target="_blank" rel="nofollow" href="https://amzn.to/tessdft">Link 1</a><br>
<a target="_blank" rel="nofollow" href="https://amzn.to/testws">Link 2</a><br>
<a target="_blank" rel="nofollow" href="https://amzn.to/testee">Link3</a><br>