我有一个带有常规标签的 HTML,看起来类似于:
<html>
<head> ... </head>
<body>
...some html....
<script>
window.siteRoot = "https://example.com"
</script>
</body>
</html>
现在在这个 HTML 中,我想用 example.com
替换所有绝对 URL 作为 /
的域。我怎么能这样做?
我知道我可以通过获取 anchor 标记然后更改它们的 href 来更改 anchor 标记的 href
,但在这里我想超越 anchor 标记并查找并替换绝对 URL,这可以在上面的 script
标记中找到的任何地方。我怎么能这样做?
最佳答案
html 元素 base将在这里提供帮助。
在这个例子中,我快速添加了一些内联 javascript,只是为了演示:onmouseover="console.log(this.src)"
, 这样我们就可以在鼠标悬停时检查 url。
但同样,它是纯 html。它将应用于文档中的所有相关 url。如果您需要为特定元素避免它,请传入完整的 url ( <img src="https://otherdomain.com/..."
)
您将看到 img
的 src url成为https://example.com/img.jpg
<html>
<head>
<base href="https://example.com">
</head>
<body>
...some html....
<img src="img.jpg" onmouseover="console.log(this.src)">
<br>
<img src="https://otherdomain.com/remote.png" onmouseover="console.log(this.src)">
</body>
</html>
请注意,它可能会导致脚本等异常,当它变得复杂时通常会有点难以使用。
关于javascript - 更改 HTML 中任何位置的所有绝对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442585/