如何自动向每个_blank链接添加图标?

时间:2019-04-28 14:18:15

标签: javascript jquery html css

我在页脚中添加了以下脚本,该脚本会自动将target =“ _ blank”添加到每个外部链接:

<script type="text/javascript">
    function linkopener(a) {
    var b = a ? "_blank" : "_self";
    var c = document.links;
    for (var i = 0; i < c.length; i++) {
        if (c[i].href.search("www.mydomain.tld") == -1) {
            c[i].addEventListener("click", function () {
                    this.target = b;
            });
         }
    }
};
$(document).ready(function(){
    linkopener(true);
});
</script>

现在,我想在每个链接的末尾将其扩展为一个小指示器,以使用户意识到这是一个外部链接,为此,我找到了以下解决方案:https://stackoverflow.com/a/52058198但我无法做到工作。如何将其集成到我的工作脚本中?

1 个答案:

答案 0 :(得分:1)

我希望这段代码对您有帮助

function linkopener(a) {
    var b = a ? "_blank" : "_self";
    var c = document.links;
    for (var i = 0; i < c.length; i++) {
        if (c[i].href.search("www.mydomain.tld") == -1) {
            /*
            c[i].addEventListener("click", function () {
                    this.target = b;
            });
            */
            c[i].target = b;
            c[i].className += ' external-link' 
         }
    }
};
$(document).ready(function(){
    linkopener(true);
});
a.external-link {
  position: relative;
  padding-right: 20px;
}
a.external-link:after {
  content: '\2197';
  position: absolute;
  right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.google.com">Google</a>
<a href="https://www.facebook.com">Facebook</a>
<a href="https://www.stackoverflow.com">StackOverflow</a>
<a href="https://www.medium.com">Medium</a>
<a href="www.mydomain.tld">My domain</a>