Foros del Web » Programando para Internet » Javascript »

Añadir enlace JS en HTML

Estas en el tema de Añadir enlace JS en HTML en el foro de Javascript en Foros del Web. Hola. Necesito saber como añadir un hipervínculo (enlace, link) de un código javascript y aplicarlo a un HTML. Es decir, yo tengo el siguiente código: ...
  #1 (permalink)  
Antiguo 03/09/2013, 18:37
Avatar de NueveReinas  
Fecha de Ingreso: septiembre-2013
Ubicación: No tan Buenos Aires
Mensajes: 1.101
Antigüedad: 10 años, 7 meses
Puntos: 145
Exclamación Añadir enlace JS en HTML

Hola.

Necesito saber como añadir un hipervínculo (enlace, link) de un código javascript y aplicarlo a un HTML.
Es decir, yo tengo el siguiente código:

[Extracto del código completo]
Código:
<head>
<script language="JavaScript">
var foto = new Array();
foto[0] = "Imagenes/Azul1.jpg";
foto[1] = "Imagenes/Blanco2.jpg";
</script>
</head>
[Extracto del código completo]
Código:
<body>
<a href="http://www.google.es/"><img id="misfotos" src="Imagenes/Azul1.jpg" /></a>
</body>
El asunto es que, como podéis deducir, es una galería de imágenes.
Lo que yo necesito es que al hacer click en la foto 1 (Azul1.jpg) me abra, por ejemplo, Google. Y al hacer click en la segunda foto (Blanco2.jpg) me abra YouTube.

¿Cómo le asigno un enlace a cada foto?
Porque, si veis el segundo código, yo he asignado un HREF a la primera foto, pero si paso a la segunda, el enlace es el mismo, pues tiene aplicado el ID que contiene el código para pasar una imagen a otra.
Necesitaría saber el código que hay que agregar en JS y el valor en HTML.

Gracias de antebrazo.
  #2 (permalink)  
Antiguo 04/09/2013, 01:11
 
Fecha de Ingreso: agosto-2013
Mensajes: 150
Antigüedad: 10 años, 8 meses
Puntos: 29
Respuesta: Añadir enlace JS en HTML

Podría ser algo así:
Código Javascript:
Ver original
  1. var fotos = [["ruta/foto1.jpg","ref1"],["ruta/foto2.jpg","ref2"]];
  2.  
  3. function fotos(string) {
  4.  
  5.    for (var i = 0; i < fotos.length; i++) {
  6.          document.write("<a href='" + fotos[i][1] + "'><img id='misfotos' src='" + fotos[i][0] + "' /></a>");
  7.          document.write('<br>');
  8.    };
  9. }

Esta línea:
<a href="http://www.google.es/"><img id="misfotos" src="Imagenes/Azul1.jpg" /></a>
Por:
<script language="JavaScript">fotos();</script>

Última edición por bathorz; 04/09/2013 a las 01:50 Razón: un error en el código
  #3 (permalink)  
Antiguo 04/09/2013, 08:28
Avatar de NueveReinas  
Fecha de Ingreso: septiembre-2013
Ubicación: No tan Buenos Aires
Mensajes: 1.101
Antigüedad: 10 años, 7 meses
Puntos: 145
Respuesta: Añadir enlace JS en HTML

Lo he hecho de la siguiente manera:

Código:
<script language="JavaScript">
var fotos = [["ruta/Imagenes/Azul1.jpg","http://www.google.es/"],["ruta/Imagenes/Blanco2.jpg","http://www.youtube.com/"]];
 
function fotos(string) {
 
   for (var i = 0; i < fotos.length; i++) {
         document.write("<a href='" + fotos[i][1] + "'><img id='misfotos' src='" + fotos[i][0] + "' /></a>");
         document.write('<br>');
   };
}

</script>
Código:
<script language="JavaScript">fotos();</script>
Pero no me funciona. ¿Qué falla?
Y no entiendo porque en el body está ese script, ni porque llamar a las imágenes dos veces... Soy un novato bastante confuso.

p.d.: También he probado sin el ruta/, pero aún así no lo entiendo.
  #4 (permalink)  
Antiguo 04/09/2013, 14:38
 
Fecha de Ingreso: agosto-2013
Mensajes: 150
Antigüedad: 10 años, 8 meses
Puntos: 29
Respuesta: Añadir enlace JS en HTML

/ruta era una carpeta que estaba en lugar de /Imagenes.
No llama a las imágenes 2 veces. La función imprime tantas etiquetas <a> como registros haya en el array. Lee sobre funciones y bucles.
Código HTML:
Ver original
  1.    <head>
  2.       <script language="JavaScript">
  3.          var fotos = new Array();
  4.          fotos = [["Imagenes/Azul1.jpg", "http://www.google.es/"], ["Imagenes/Blanco2.jpg", "http://www.youtube.com/"]];
  5.  
  6.          function fotos(string) {
  7.             for (var i = 0; i < fotos.length; i++) {
  8.               document.write("<a href='" + fotos[i][1] + "'><img id='misfotos' src='" + fotos[i][0] + "' /></a>");
  9.                document.write("<br>");
  10.             };
  11.          }
  12.       </script>
  13.    </head>
  14.    <body>
  15.       <script language="JavaScript">
  16.          fotos();
  17.       </script>
  18.    </body>
  19. </html>
  #5 (permalink)  
Antiguo 05/09/2013, 07:14
 
Fecha de Ingreso: agosto-2013
Mensajes: 150
Antigüedad: 10 años, 8 meses
Puntos: 29
Respuesta: Añadir enlace JS en HTML

Funcionamiento
Código txt:
Ver original
  1. a) De arranque
  2. ------------
  3.  [ foto 1 ]  <-- enlace www.dos.es
  4.   [ ¡Uno ]   <-- enlace www.google.es
  5. [<<]    [>>]
  6. ------------
  7.  
  8. b) Al primer cambio
  9. ------------
  10.  [ foto 2 ]  <-- enlace www.dos.es
  11.  [ texto2 ]  <-- sin enlace
  12. [<<]    [>>]
  13. ------------

Código HTML:
Ver original
  1.    <head>
  2.       <script language="JavaScript">
  3.      
  4.          var foto = new Array();
  5.          /** 1. modificado: array bidimencional **/
  6.          foto = [
  7.             ["Imagenes/Azul1.jpg", "http://www.uno.es/"],
  8.             ["Imagenes/Blanco2.jpg", "http://www.dos.com/"],
  9.             ["Imagenes/Deg3.jpg", "http://www.tres.com/"],
  10.             ["Imagenes/Negro4.jpg", "http://www.cuatro.com/"],
  11.             ["Imagenes/Rojo5.jpg", "http://www.cinco.com/"],
  12.             ["Imagenes/Verde6.jpg", "http://www.seis.com/"]];
  13.          
  14.          var texto = new Array();
  15.          texto[0] = "la primera de las imagenes";
  16.          texto[1] = "esta es la segunda";
  17.          texto[2] = "esta es al tercera";
  18.          texto[3] = "y casi vamos a terminar";
  19.          texto[4] = "una más";
  20.          texto[5] = "la ultima de las imagenes";
  21.  
  22.          var cantidad = foto.length;
  23.          var cualvemos = 0;
  24.  
  25.          function mover(direccion) {
  26.          
  27.             /** 2. enlace **/
  28.             var enlace = document.getElementById("misHref");
  29.  
  30.             var laimagen = document.getElementById("misfotos");
  31.             var eltexto = document.getElementById("mistextos");
  32.             var ultima = foto.length - 1;
  33.             var auxiliar = cualvemos + (direccion);
  34.             if (auxiliar < 0) {
  35.               auxiliar = ultima;
  36.            }
  37.            if (auxiliar > ultima) {
  38.                auxiliar = 0;
  39.             }
  40.             cualvemos = auxiliar;
  41.  
  42.             /** 3. cambio por array bidimencional **/
  43.             laimagen.src = foto[cualvemos][0];
  44.  
  45.             eltexto.innerHTML = texto[cualvemos];
  46.            
  47.             /** 4. enlace foto **/
  48.             enlace.href = foto[cualvemos][1];
  49.          }
  50.  
  51.       </script>
  52.       <meta charset="UTF-8">
  53.       <title>Destacados</title>
  54.    </head>
  55.  
  56.    <body onLoad="mover;">
  57.       <table width="100%">
  58.          <tr>
  59.             <td height="279" align="center" valign="middle">
  60.                <table width="100%" align="center">
  61.                   <tr>
  62.                      <td width="17%" height="256" align="center" valign="middle">
  63.                         <p>
  64.                            <a id="misHref" href="http://www.uno.com/"><img id="misfotos" src="Imagenes/1.jpg" /></a>
  65.                         </p>
  66.                         <p>
  67.                            <span id="mistextos"><a href="http://www.google.es/">¡Uno</a></span>
  68.                         </p>
  69.                         <p>
  70.                            <a href="javascript:mover(-1);"><img src="Imagenes/anterior.png"></img></a>
  71.                            <a href="javascript:mover(1);"><img src="Imagenes/siguiente.png"</img></a>
  72.                         </p></td>
  73.                     <!--
  74.                    <td width="83%" align="center" valign="middle"></td>
  75.                    -->
  76.                   </tr>
  77.                </table></td>
  78.          </tr>
  79.       </table>
  80.    </body>
  81. </html>
  #6 (permalink)  
Antiguo 05/09/2013, 08:08
Avatar de NueveReinas  
Fecha de Ingreso: septiembre-2013
Ubicación: No tan Buenos Aires
Mensajes: 1.101
Antigüedad: 10 años, 7 meses
Puntos: 145
Respuesta: Añadir enlace JS en HTML

Genial, funciona bien. Solo tengo una duda.
Si yo tengo varias galerías como esa, en las que hay diferentes fotos, ¿cómo puedo desvincular el botón anterior/siguiente de la Galería 1 con los botones de la Galería 2?
  #7 (permalink)  
Antiguo 05/09/2013, 09:45
 
Fecha de Ingreso: agosto-2013
Mensajes: 150
Antigüedad: 10 años, 8 meses
Puntos: 29
Respuesta: Añadir enlace JS en HTML

Código HTML:
Ver original
  1.    <head>
  2.       <script language="JavaScript">
  3.          var foto = new Array();
  4.          foto = [["Imagenes/1.jpg", "http://www.uno.es/"], ["Imagenes/2.jpg", "http://www.dos.com/"], ["Imagenes/3.jpg", "http://www.tres.com/"], ["Imagenes/4.jpg", "http://www.cuatro.com/"], ["Imagenes/5.jpg", "http://www.cinco.com/"], ["Imagenes/6.jpg", "http://www.seis.com/"]];
  5.          var texto = new Array();
  6.          texto[0] = "la primera de las imagenes";
  7.          texto[1] = "esta es la segunda";
  8.          texto[2] = "esta es al tercera";
  9.          texto[3] = "y casi vamos a terminar";
  10.          texto[4] = "una más";
  11.          texto[5] = "la ultima de las imagenes";
  12.          var cantidad = foto.length;
  13.          var cualvemos = 0;
  14.  
  15.          function mover(direccion, valor) {
  16.             switch (valor) {
  17.                /** Galería 1 **/
  18.                case 1:
  19.                   var enlace = document.getElementById("misHref");
  20.                   var laimagen = document.getElementById("misfotos");
  21.                   var eltexto = document.getElementById("mistextos");
  22.                   var ultima = foto.length - 1;
  23.                   var auxiliar = cualvemos + (direccion);
  24.                   if (auxiliar < 0) {
  25.                     auxiliar = ultima;
  26.                  }
  27.                  if (auxiliar > ultima) {
  28.                      auxiliar = 0;
  29.                   }
  30.                   cualvemos = auxiliar;
  31.                   laimagen.src = foto[cualvemos][0];
  32.                   eltexto.innerHTML = texto[cualvemos];
  33.                   enlace.href = foto[cualvemos][1];
  34.                   break;
  35.                /** Galería 1 **/
  36.                case 2:
  37.                   var enlace = document.getElementById("misHref2");
  38.                   var laimagen = document.getElementById("misfotos2");
  39.                   var eltexto = document.getElementById("mistextos2");
  40.                   var ultima = foto.length - 1;
  41.                   var auxiliar = cualvemos + (direccion);
  42.                   if (auxiliar < 0) {
  43.                     auxiliar = ultima;
  44.                  }
  45.                  if (auxiliar > ultima) {
  46.                      auxiliar = 0;
  47.                   }
  48.                   cualvemos = auxiliar;
  49.                   laimagen.src = foto[cualvemos][0];
  50.                   eltexto.innerHTML = texto[cualvemos];
  51.                   enlace.href = foto[cualvemos][1];
  52.                   break;
  53.             }
  54.          }
  55.       </script>
  56.       <meta charset="UTF-8">
  57.       <title>Destacados</title>
  58.    </head>
  59.  
  60.    <body onLoad="mover;">
  61.       <table width="100%">
  62.          <tr>
  63.             <td height="279" align="center" valign="middle">
  64.             <table width="100%" align="center">
  65.                <tr>
  66.                   <!-- Galería 1 -->
  67.                   <td width="50%" height="256" align="center" valign="middle">
  68.                   <p>
  69.                      <a id="misHref" href="http://www.uno.com/"><img id="misfotos" src="Imagenes/1.jpg" /></a>
  70.                   </p>
  71.                   <p>
  72.                      <span id="mistextos"><a href="http://www.google.es/">¡Uno</a></span>
  73.                   </p>
  74.                   <p>
  75.                      <a href="javascript:mover(-1,1);"><img src="Imagenes/anterior.png"></img></a>
  76.                      <a href="javascript:mover(1,1);"><img src="Imagenes/siguiente.png"</img></a>
  77.                   </p></td>
  78.                   <!-- Galería 2-->
  79.                   <td width="50%" height="256" align="center" valign="middle">
  80.                   <p>
  81.                      <a id="misHref2" href="http://www.uno.com/"><img id="misfotos2" src="Imagenes/1.jpg" /></a>
  82.                   </p>
  83.                   <p>
  84.                      <span id="mistextos2"><a href="http://www.google.es/">¡Dos</a></span>
  85.                   </p>
  86.                   <p>
  87.                      <a href="javascript:mover(-1,2);"><img src="Imagenes/anterior.png"></img></a>
  88.                      <a href="javascript:mover(1,2);"><img src="Imagenes/siguiente.png"</img></a>
  89.                   </p></td>
  90.                </tr>
  91.             </table></td>
  92.          </tr>
  93.       </table>
  94.    </body>
  95. </html>

Etiquetas: enlace, html, js
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:47.