¿Cómo puedo crear un enlace usando javascript?


Tengo una cadena para un título y una cadena para un enlace. No estoy seguro de cómo poner los dos juntos para crear un enlace en una página usando Javascript. Cualquier ayuda es apreciada.

EDIT1: Añadir más detalles a la pregunta. La razón por la que estoy tratando de averiguar esto es porque tengo una fuente RSS y tengo una lista de títulos y URLs. Me gustaría vincular los títulos a la URL para que la página sea útil.

EDIT2: Estoy usando jQuery pero soy completamente nuevo en él y no era consciente de que podría ayuda en esta situación.

Author: Xavier, 2011-01-23

7 answers

<html>
<head></head>
<body>
<script>

var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);

</script>
</body>
</html>
 181
Author: Jared Farrish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 17:34:59

Con JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML = desiredText;
    // apend the anchor to the body
    // of course you can append it almost to any other dom element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    O, como sugiere @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

Con jQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. var a = $('<a />');
    a.attr('href',desiredLink);
    a.text(desiredText);
    $('body').append(a);
    

En todos los ejemplos anteriores puede agregar el ancla a cualquier elemento, no solo al 'cuerpo', y desiredLink es una variable que contiene la dirección a la que apunta su elemento de ancla, y desiredText es una variable que contiene el texto que será se muestra en el elemento ancla.

 44
Author: gion_13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:31

Crear enlaces usando JavaScript:

<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>

O

<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>

O

<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
 12
Author: Naveed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-24 22:58:41

Hay un par de maneras:

Si desea utilizar Javascript sin formato (sin un ayudante como jQuery), entonces podría hacer algo como:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

El otro método es escribir el enlace directamente en el documento:

document.write("<a href='" + link + "'>" + text + "</a>");
 8
Author: Roopinder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-23 07:52:27

Crea dinámicamente un hipervínculo con JavaScript raw:

   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body
 1
Author: jmort253,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-23 07:46:38

    <script>
      _$ = document.querySelector  .bind(document) ;

        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
        var a   =  document.createElement( 'a' )
        a.text  = "Download example" 
        a.href  = "//bit\.do/DeezerDL"

        AppendLinkHere.appendChild( a )
        

     // a.title = 'Well well ... 
        a.setAttribute( 'title', 
                         'Well well that\'s a link'
                      );
    </script>
  1. El 'Objeto de anclaje' tiene sus propias propiedades* (heredadas) * para establecer el enlace, su texto. Así que úsalos. .setAttribute es más general, pero normalmente no lo necesita. a.title ="Blah" hará lo mismo y es más claro! Bueno, una situación que va a exigir .setAttribute es esto: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Deja el protocolo abierto. En lugar de http://example.com/path considere solo usar //example.com/path. Comprobar si example.com se puede acceder por http: así como https: pero el 95% de los sitios funcionarán en ambos.

  3. OffTopic: Eso no es realmente relevante acerca de la creación de enlaces en JS pero tal vez es bueno saberlo: Bueno, a veces, como en la consola de desarrollo de chromes, puedes usar $("body") en lugar de document.querySelector("body") Un _$ = document.querySelector 'honrará' tus esfuerzos con un error Invocación ilegal la primera vez que lo uses. Eso es porque la tarea solo 'agarra' .querySelector (una referencia al método class). Con .bind(... también involucrarás el contexto (aquí es document) y obtendrás un método object que funcionará como esperarías.

 1
Author: Nadu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 17:29:27

Pegas esto dentro:

<A HREF = "index.html">Click here</A>

 -4
Author: zerodunwash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-24 18:11:58