试图替换文档中的每一个href

Trying to replace every href on the document

本文关键字:每一个 href 文档 替换      更新时间:2023-09-26

我对Javascript完全陌生,我想创建一个Greasemonkey脚本,将文档的所有href元素上的"/text/othertext/"替换为"/text2/text3"。这就是我想出来的,正如我所料,它不起作用:

var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
 {
   var gethref = links[i].getAttribute('href');
   gethref = gethref.replace(/text'/othertext/g,'text2'/text3');
   links[i].setAttribute("href", gethref);
  }

提前感谢!


编辑:好吧,我知道为什么我的脚本不工作,但我不知道它是否可以修复,我正试图替换页面完全加载后加载的元素(也许是ajax?)https://i.stack.imgur.com/Kjm6P.png

此代码有效。您的代码看起来也不错。也许您是在文档元素之前加载脚本?注意我的元素是如何列在脚本前面的:

<a href="before">link</a>
<a href="before">link</a>
<script>
    var links = document.getElementsByTagName('a');
    for(var i = 0; i < links.length; i++) {
        var href = links[i].getAttribute('href');
        href = href.replace('before', '#');
        links[i].setAttribute('href', href);
    }
</script>

编辑,根据您的评论,在运行脚本之前,使用setTimeout函数来修复导致应用程序延迟的脏修复。例如,要延迟五秒钟,您可以这样使用:

<a href="before">link</a>
<a href="before">link</a>
<script>
    setTimeout(function() {
        var links = document.getElementsByTagName('a');
        for(var i = 0; i < links.length; i++) {
            var href = links[i].getAttribute('href');
            href = href.replace('before', '#');
            links[i].setAttribute('href', href);
        }
    }, 5000); // < --- note the time in ms here
</script>

不太确定为什么你的代码不能工作。

我整理了下面的代码片段,可能会有帮助。

(function() {
  var anchors = document.querySelectorAll('a');
  for(var i = 0; i < anchors.length; i++) {
    var newHref = anchors[i].getAttribute('href').replace(/text'/othertext/g,'text2'/text3');
    anchors[i].setAttribute('href', newHref);
  }
}());
a {
  display: block;
}
<!DOCTYPE html>
<head></head>
<body>
  <a href="text/othertext">Some link</a>
  <a href="egerg">Some other link</a>
</body>

如果你运行这段代码,你会看到只有一个锚被正确地更新了。

希望这对你有帮助!

最简单的解决方案是这样包装代码:

window.onload = function(){
    /* your code here */
};

这将确保你的代码(特别是如果你把你的脚本放在文档的末尾)不会加载,直到整个页面(包括文本,图像等)。

window.onload = function() {
  document.body.innerHTML = document.body.innerHTML
    .replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
  <a href="text/othertext/">Some link</a>
  <a href="egerg">Some other link</a>
</body>