2012-03-22 14 views
7

Sto provando ad impostare il mio testo come collegamento in modo che quando faccio clic su di esso, viene eseguita una funzione. In questo momento ho appena impostato su google.com per cercare di far apparire il testo come un collegamento, ma sembra che non stia facendo nulla. È solo un testo statico. Eventuali suggerimenti?Crea dinamicamente collegamento 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 collegamento a un altro sito, credo, deve utilizzare un URI completo nome/dominio: 'google.com' ha bisogno di essere' http: // google.com' per il 'href' colleghi tramite link Google. –

+0

Viene ancora visualizzato come testo statico anziché come collegamento. – mkyong

+0

Non si inserisce mai il collegamento nel documento, ma solo il nodo di testo. 'a.appendChild' restituisce il nodo appena aggiunto. –

risposta

0

Prova questo fuori: 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

Guardate questo esempio:

http://jsfiddle.net/ajXEW/

ho aggiunto alcuni commenti all'interno del codice che spiegano le fasi differenti.

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

Ha funzionato. Grazie! – mkyong

+0

Ho aggiornato la risposta con alcuni nuovi commenti nel codice. –

Problemi correlati