gpt4 book ai didi

javascript - 在点击此链接后,在绑定(bind)到 anchor 链接的 onclick 函数中获取 URL/ anchor

转载 作者:行者123 更新时间:2023-11-27 23:32:43 25 4
gpt4 key购买 nike

上下文

CSS 缺少“a:current”选择器或对当前 URL 的访问,因此我尝试编写 vanilla JS 代码来为我的菜单中链接到同一页面/ anchor 的链接着色。

每次单击 anchor 链接时,我都会运行一个函数来检查每个菜单链接是否与新 anchor 对应。问题:document.URL 在单击链接之前引用了 URL。请注意,我认为我可以用不同的方式为我的链接着色,但这不是问题的一部分(如果您有建议,可以发表评论)。

重现代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />
</head>
<body>
<script>
var check_anchor = function()
{
document.getElementById('url_log').innerHTML = document.URL;
}
</script>
<a href='#anchor_1' onclick='check_anchor();'>Anchor 1</a>
<a href='#anchor_2' onclick='check_anchor();'>Anchor 2</a>
<a href='#anchor_3' onclick='check_anchor();'>Anchor 3</a>
<p>URL is <span id='url_log'></span></p>
</body>
</html>

示例:

当您单击 anchor 2 时:“file:///home/[...]/Anchor_Example.html”

当您单击 anchor 3 时:“file:///home/[...]/Anchor_Example.html#anchor_2”

当您单击 anchor 1 时:“file:///home/[...]/Anchor_Example.html#anchor_3”

当您单击 anchor 1 时:“file:///home/[...]/Anchor_Example.html#anchor_1”

(按此顺序:有“延迟”:打印的 URL 是单击链接之前的 URL。我想要的是当您单击 anchor 1 时:“file:///home/[...]/Anchor_Example.html#anchor_1")

问题

是否可以在点击 anchor 链接后轻松获取 URL,或者在点击链接后调用 onClick 事件?如果是这样,你会怎么做?

如果这个问题看起来很愚蠢或者已经有人回答了(我没有成功地寻找它),我很抱歉。

最佳答案

这就是 window.onhashchange 派上用场的地方。

Check it out on MDN

根本不是一个愚蠢的问题。

在该事件处理程序中,任何时候您想知道新的 URL 是什么,您可以使用 location.href 或使用 location 获取更改的部分(散列)。散列

window.onhashchange = function () {
console.log(location.hash); // new hash/anchor location
}

关于javascript - 在点击此链接后,在绑定(bind)到 anchor 链接的 onclick 函数中获取 URL/ anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com