javascript - 更改页面上的特定链接
问题描述
我是编码新手,对 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 */
}
}
}
任何帮助将非常感激。谢谢
解决方案
两件事情:
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 */
}
}
};
推荐阅读
- pojo - POJO 对象中的空值
- javascript - Javascript/Typescript 滚动到 DIV 的底部
- java - 三星 S21 camera2 API 问题与近物体
- python-3.x - 从 Jupyter 到终端 .py
- python - 适合在python中没有达到顶峰
- python-3.x - 错误:找不到满足要求 cxvpy 的版本(来自版本:无)
- web-scraping - 如何使用 Scrapy 抓取具有多个类的 div
- json - Jenkins - 扩展选择参数 - Groovy 脚本:外部 JSON 默认值
- visual-studio-code - 无论如何配置 VS Code 以在访问服务器时使用 OKTA?
- powershell - PowerShell SAST / OWASP 10