2010-04-12 105 views
2

如何爲使用以下javascript創建的圖像添加鏈接。如何使用javascript添加鏈接到使用javascript創建的圖像元素

感謝您的任何幫助或答覆。

for(var i=0; i<images.length; i++) { 
    var t = document.createElement('IMG'); 
    t.setAttribute('src',images[i]); 
    t.setAttribute('border', 0); 
    t.setAttribute('width',imageWidth); 
    t.setAttribute('height',imageHeight); 
    t.style.position = 'absolute'; 
    t.style.visibility = 'hidden'; 

    el.appendChild(t); 
} 
+1

它不在HTML文檔上使用'setAttribute'是個好主意。有很多情況下,這在IE中失敗(儘管不是你打的)。首選DOM Level 1 HTML屬性:'t.src = images [i];'等 – bobince 2010-04-12 11:04:07

回答

5

試試這個:

for(var i=0; i<images.length; i++) 
{ 

    var t = document.createElement('IMG'); 
    var link = document.createElement('a'); // create the link 
    link.setAttribute('href', 'www.example.com'); // set link path 
    // link.href = "www.example.com"; //can be done this way too 

    t.setAttribute('src',images[i]); 
    t.setAttribute('border', 0); 
    t.setAttribute('width',imageWidth); 
    t.setAttribute('height',imageHeight); 
    t.style.position = 'absolute'; 
    t.style.visibility = 'hidden'; 

    link.appendChild(t); // append to link 
    el.appendChild(link); 
} 
0

以同樣的方式創建一個a元素。將它附加到el而不是圖像,並將圖像追加到它。

0

您需要先創建一個錨元素,則img元素追加到它......像這樣:

for(var i=0; i<images.length; i++) { 
    var a = document.createElement('a'); 
    a.href = "http://www.MYWEBSITE.com/" 
    var t = document.createElement('IMG'); 
    t.setAttribute('src',images[i]); 
    t.setAttribute('border', 0); 
    t.setAttribute('width',imageWidth); 
    t.setAttribute('height',imageHeight); 
    t.style.position = 'absolute'; 
    t.style.visibility = 'hidden'; 
    a.appendChild(t); 
    el.appendChild(a); 
} 

然後追加錨「厄爾尼諾」

馬特

相關問題