2012-03-22 10 views
7

Estoy tratando de establecer mi texto como un enlace para que cuando haga clic en él, ejecute una función. Ahora mismo lo tengo configurado en google.com para intentar que el texto aparezca como un enlace, pero no parece estar haciendo nada. Es solo texto estático. ¿Alguna sugerencia?Cree dinámicamente el enlace Javascript

 var leftDiv = document.createElement("div"); //Create left div 
     leftDiv.id = "left"; //Assign div id 
     leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes 
     leftDiv.style.background = divColor; 
     a = document.createElement('a'); 
     a.setAttribute('href', 'google.com'); 
     user_name = a.appendChild(document.createTextNode(fullName + ' ')); 

     leftDiv.appendChild(user_name); // Add name to left div 
+1

un enlace a otro sitio, creo, tiene que usar un URI Nombre/dominio completo: 'google.com' necesita ser' http: // google.com' para el 'href' vincular Google. –

+0

Todavía aparece como texto estático en lugar de un enlace. – mkyong

+0

Nunca está insertando el enlace en el documento, solo el nodo de texto. 'a.appendChild' devuelve el nodo que acaba de anexarse. –

Respuesta

0

Trate de hacer esto: http://jsfiddle.net/HknMF/5/

var divColor = "red"; 
var fullName = "bob"; 

var leftDiv = document.createElement("div"); //Create left div 
     leftDiv.id = "left"; //Assign div id 
     leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes 
     leftDiv.style.background = divColor; 
     a = document.createElement('a'); 
     a.setAttribute('href', 'google.com'); 
     a.appendChild(document.createTextNode(fullName + ' ')); 

     leftDiv.appendChild(a); // Add name to left div 

    document.body.appendChild(leftDiv); 
18

vistazo a este ejemplo:

http://jsfiddle.net/ajXEW/

he añadido algunos comentarios en el código que explican los pasos diffrent.

var leftDiv = document.createElement("div"); //Create left div 
    leftDiv.id = "left"; //Assign div id 
    leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes 
    leftDiv.style.background = "#FF0000"; 
    a = document.createElement('a'); 
    a.href = 'google.com'; // Insted of calling setAttribute 
    a.innerHTML = "Link" // <a>INNER_TEXT</a> 
    leftDiv.appendChild(a); // Append the link to the div 
    document.body.appendChild(leftDiv); // And append the div to the document body 
+0

Funcionó. ¡Gracias! – mkyong

+0

Actualicé la respuesta con algunos comentarios nuevos en el código. –

Cuestiones relacionadas