Comment changer href de <a> tag sur le bouton cliquez sur javascript

Comment modifier la href attribut href d'une balise <a/> via Javascript sur le clic du bouton?

 <script type="text/javascript"> function f1() { document.getElementById("abc").href="xyz.php"; } </script> <a href="" id="abc">jhg</a> <a href="" id="" onclick="f1()">jhhghj</a> 

    Sans avoir href , le clic va recharger la page actuelle, donc vous avez besoin de quelque chose comme ceci:

     <a href="#" onclick="f1()">jhhghj</a> 

    Ou empêcher le défilement comme ceci:

     <a href="#" onclick="f1(); return false;">jhhghj</a> 

    Ou return false dans votre fonction f1 et:

     <a href="#" onclick="return f1();">jhhghj</a> 

    …. ou, la manière discrète:

     <a href="#" id="abc">jhg</a> <a href="#" id="myLink">jhhghj</a> <script type="text/javascript"> document.getElementById("myLink").onclick = function() { document.getElementById("abc").href="xyz.php"; return false; }; </script> 

    Exactement ce que Nick Carver a fait là mais je pense qu'il serait préférable d'utiliser la méthode DOM setAttribute.

     <script type="text/javascript"> document.getElementById("myLink").onclick = function() { var link = document.getElementById("abc"); link.setAttribute("href", "xyz.php"); return false; } </script> 

    C'est une ligne de code supplémentaire, mais la trouve mieux en fonction de la structure.

    Supprimer l'attribut href :

     <a id="" onclick="f1()">jhhghj</a> 

    Si les styles de lien sont importants, alors:

     <a href="javascript:void(f1())">jhhghj</a> 

    Je connais sa petite publication. Pourtant, cela pourrait aider quelqu'un.

    Au lieu d'étiqueter, si possible, vous pouvez également le faire.

      <script type="text/javascript"> function IsItWorking() { // Do your stuff here ... alert("YES, It Works...!!!"); } </script> `<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"` `runat="server">IsItWorking?</asp:HyperLink>` 

    Des commentaires à ce sujet?

    Pour qu'un lien change dynamiquement en cliquant dessus:

     <input type="text" id="emailOfBookCustomer" style="direction:RTL;"></input> <a onclick="this.href='<%= request.getContextPath() %>/Jahanpay/forwardTo.jsp?handle=<%= handle %>&Email=' + document.getElementById('emailOfBookCustomer').value;" href=''> A dynamic link </a> 
     <a href="#" id="a" onclick="ChangeHref()">1.Change 2.Go</a> <script> function ChangeHref(){ document.getElementById("a").setAttribute("onclick", "location.href='http://religiasatanista.ro'"); } </script>