如何使用javascript向使用javascript创建的图像元素添加链接

如何使用javascript向使用javascript创建的图像元素添加链接,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('heigh

如何为使用以下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);
}
for(var i=0;i试试这个:

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

for(var i=0;i以相同的方式创建
a
元素。将其附加到
el
而不是图像,并将图像附加到它。

您需要首先创建锚元素,然后将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);
}

for(var i=0;iIt在HTML文档上使用
setAttribute
不是一个好主意。在IE中有很多这样做失败的情况(尽管不是您在这里遇到的情况)。首选DOM级别1 HTML属性:
t.src=images[i];
等等。