2010-12-06 8 views
75

¿Cómo cambiar el valor de atributo href de una etiqueta <a/> a través de Javascript en el botón clic?Cómo cambiar href de <a> etiqueta en el botón haga clic en javascript

<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> 
+0

El Camino de Accesibilidad dicta a no utilizar los enlaces de esta manera. Aquí: http://xkr.us/js/links –

Respuesta

112

Sin tener un href, el clic se volverá a cargar la página actual, por lo que necesita algo como esto:

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

o prevenir el desplazamiento de esta manera:

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

O return false en su función f1 y:

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

.... o, la forma discreta:

<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> 
5

quitar href atributo:

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

si estilos de enlace son importantes a continuación:

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

Salir del href cambiará su estilo y comportamiento. Luego actúa como un ancla en lugar de un enlace. –

+1

Gracias por responder que ustedes realmente me ayudan. – Chauhan

21

Exactamente lo que Nick Carver lo hice pero creo que sería mejor si usara el método DOM setAttribute.

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

Es una línea adicional de código, pero es mejor para la estructura.

+7

IMO no es necesario aquí, esta ha sido una propiedad DOM para siempre, '.href' funciona en todos los navegadores ... por ejemplo, usted usaría' .getAttribute ("id") 'en lugar de solo' .id'? :) –

+2

Tienes razón, no hace nada especial o diferente, es solo estructural.Me gusta tener todas mis funciones DOM de esta manera para una depuración/revisión posterior: es más fácil para mí ver qué está haciendo la función con estos métodos. Obviamente su respuesta es correcta en el dinero :) – jakobhans

+2

Gracias por responder Señor. – Chauhan

0

Sé que es un poco viejo post. Aún así, podría ayudar a alguien.

En lugar de la etiqueta, si es posible, puede hacer esto también.

<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>` 

Cualquier comentario sobre esto?

0

tener un enlace cambiar dinámicamente en hacer clic en él:

<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> 
0
<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> 
0

Aquí está mi opinión sobre ella. Necesitaba crear una URL recolectando el valor de un cuadro de texto, cuando el usuario presiona un botón Enviar.

<html> 
 
<body> 
 

 
Hi everyone 
 

 
<p id="result"></p> 
 

 
<textarea cols="40" id="SearchText" rows="2"></textarea> 
 

 
<button onclick="myFunction()" type="button">Submit!</button> 
 

 
<script> 
 
function myFunction() { 
 
    var result = document.getElementById("SearchText").value; 
 
\t document.getElementById("result").innerHTML = result; 
 
\t document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result; 
 
} \t \t 
 
</script> 
 

 

 
<a href="#" id="abc">abc</a> 
 

 
</body> 
 
<html>

Cuestiones relacionadas