首页 > 解决方案 > 更改页面上的特定链接

问题描述

我是编码新手,对 JavaScript 也是如此。

我试图在 Stack Overflow 上找到我的问题的解决方案,但只找到了部分问题的答案。我在下面修补了一个显然不起作用的代码。

我的目标是在 href 属性中选择具有特定域的网页上的链接,然后更改所选链接的 href,以便只保留 url 字符串的前 106 个字符和一个新位(“groupid=provider”)添加到它。这些链接也应该接收值为“wrongLink”的类属性。在我加载具有以下脚本的网页时,网页上的每个链接都会受到影响,无论链接的 url 中的域如何。

代码:

window.onload = function() {
       /* onload code */

var anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {
    var urltobechanged = anchors[i].href;  
       /* urltobechanged to store the url */

    var domaincheck = urltobechanged.startsWith("example.com");

    if (domaincheck = true){
       /* if the stored url starts with "example.com", then.. */

        anchors[i].href = urltobechanged.substring(0,105) + "groupid=provider";
       /* keep the first 106 characters of the url and add "goupid=provider" to it */

        anchors[i].setAttribute("class", "wrongLink");
       /* add class with "wrongLink" attribute to the the changed link element */
    }
}
}

任何帮助将非常感激。谢谢

标签: javascript

解决方案


两件事情:

  • if (domaincheck = true)需要是if (domaincheck)
  • 你需要.getAttribute在你的锚上使用
window.onload = function() {
    /* onload code */

    var anchors = document.getElementsByTagName("a");

    for (var i = 0; i < anchors.length; i++) {
        var urltobechanged = anchors[i].getAttribute("href");
        /* urltobechanged to store the url */

        var domaincheck = urltobechanged.startsWith("example.com");

        if (domaincheck) {
            /* if the stored url starts with "example.com", then.. */

            anchors[i].href =
                urltobechanged.substring(0, 105) + "groupid=provider";
            /* keep the first 106 characters of the url and add "goupid=provider" to it */

            anchors[i].setAttribute("class", "wrongLink");
            /* add class with "wrongLink" attribute to the the changed link element */
        }
    }
};

推荐阅读