search

Home  >  Q&A  >  body text

How to pass function to dynamically created href?

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粉571233520P粉571233520493 days ago1120

reply all(1)I'll reply

  • P粉788571316

    P粉7885713162023-09-23 00:45:10

    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

    reply
    0
  • Cancelreply