2012-03-22 16 views
7

Próbuję ustawić mój tekst jako łącze, tak, że po kliknięciu na nim uruchamia funkcję. W tej chwili ustawiam go na google.com, aby tekst był wyświetlany jako link, ale nie wydaje się, aby cokolwiek robił. To tylko tekst statyczny. Jakieś sugestie?Dynamicznie Utwórz łącze 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

link do innej strony, myślę, że musi użyć pełnej nazwy URI/dziedzina: 'google.com' musi być' http: // google.com' do podłączenia się do 'href' Google. –

+0

Nadal wyświetla się jako tekst statyczny zamiast linku. – mkyong

+0

Nigdy nie wstawiasz linku do dokumentu, tylko do węzła tekstowego. 'a.appendChild' zwraca tylko dodany węzeł. –

Odpowiedz

0

Spróbuj tego: 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

Spójrz na ten przykład:

http://jsfiddle.net/ajXEW/

I dodał kilka uwag wewnątrz kodu, które wyjaśniają rozróżnianie kroki.

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

Zadziałało. Dzięki! – mkyong

+0

Zaktualizowałem odpowiedź, dodając kilka nowych komentarzy do kodu. –

Powiązane problemy