2012-03-22 13 views
7

Metnimi bir bağlantı olarak ayarlamaya çalışıyorum, böylece üzerine tıkladığımda bir işlev çalıştırır. Şu anda sadece bir bağlantı olarak görünmesini sağlamak için google.com'a ayarlıyorum, ancak hiçbir şey yapmıyor gibi görünüyor. Bu sadece statik bir metin. Baska öneri?Dinamik Olarak Bağlantı Oluştur 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

başka bir siteye bir bağlantı, bence, bir tam tanım/alan adını kullanması gerekir // google.com' bağlamak 'href' için Google. –

+0

Yine de bir bağlantı yerine statik metin olarak görünüyor. – mkyong

+0

Bağlantıyı asla belgeye, yalnızca metin düğümüne eklemiyorsunuz. "a.appendChild", eklenmiş olan düğümü döndürür. –

cevap

0

bu deneyin: Bu örneğe 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

bak:

http://jsfiddle.net/ajXEW/

Ben diffrent adımları açıklamak kod içindeki bazı yorumlar ekledi. `` Http olması gerekiyor google.com`:

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

Çalıştı. Teşekkürler! – mkyong

+0

Yanıtı yeni bazı yorumlarla kodda güncelledim. –