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); 
} 

然后追加锚“厄尔尼诺”

马特

相关问题