How to pass function to dynamically created href?
P粉571233520
P粉571233520 2023-09-22 09:37:55
0
1
1078

I want to pass a function to the href attribute of my a tag link, but no matter what I try it doesn't work. It either results in a 404 page or is simply unclickable. What did i do wrong?

This is not clickable

<body>
<a id="specialLink" href="#" onClick="redirectToApp()">点击我</a>
<script>
document.getElementById('specialLink').href = redirectToApp();
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

This is not clickable

<body>
<a href="#" onClick="document.location.href=redirectToApp()">点击我</a>
<script>
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

This results in a 404 page

<body>
<a href="javascript:document.location.href=redirectToApp();">点击我</a>
<script>
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

I should probably also clarify that I'm emailing this HTML where the link should open, and unless I just pass the URL as a string to the href, nothing works.

P粉571233520
P粉571233520

reply all(1)
P粉788571316

You can try this:

const anchor = document.getElementById('specialLink')
anchor.addEventListener((e) => {
    e.preventDefault()
    window.open("https://google.com");

})

And remove the onClick attribute

on the anchor tag
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template