2012-03-22 6 views
7

私はリンクとしてテキストを設定しようとしているので、クリックすると関数が実行されます。今はテキストをリンクとして表示するようgoogle.comに設定していますが、何もしていないようです。それは単に静的テキストです。助言がありますか?動的にリンクの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

別のサイトへのリンクは、私が思うに、完全なURI /ドメイン名を使用する必要があります。// google.com'にリンクする 'href'用Google。 –

+0

まだリンクの代わりに静的テキストとして表示されます。 – mkyong

+0

文書にリンクを挿入することは決してありません。テキストノードだけです。 'a.appendChild'はちょうど追加されたノードを返します。 –

答えて

0

これを試してみてください:この例で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

ルック:

http://jsfiddle.net/ajXEW/

を私は切り抜いた手順を説明し、コード内のいくつかのコメントを追加しました。 `` HTTPにする必要があり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

それは働いた。ありがとう! – mkyong

+0

コードにいくつかの新しいコメントを追加して答えを更新しました。 –

関連する問題