我想将一个函数传递给我的标签链接中的 href,但无论我尝试什么,它都不起作用。它要么会导致 404 页面,要么甚至无法点击。我做错了什么?
这是不可点击的
<body>
<a id="specialLink" href="#" onClick="redirectToApp()">click me</a>
<script>
document.getElementById('specialLink').href = redirectToApp();
function redirectToApp () {
return "http://www.google.com";
}
</script>
</body>
这是不可点击的
<body>
<a href="#" onClick="document.location.href=redirectToApp()">click me</a>
<script>
function redirectToApp () {
return "http://www.google.com";
}
</script>
</body>
这会导致 404 页面
<body>
<a href="javascript:document.location.href=redirectToApp();">click me</a>
<script>
function redirectToApp () {
return "http://www.google.com";
}
</script>
</body>
你可以试试这个:
const anchor = document.getElementById('specialLink')
anchor.addEventListener((e) => {
e.preventDefault()
window.open("https://google.com");
})
并删除锚标记上的
onClick