简体   繁体   中英

how to use javascript to add link to image element created using javascript

how to add link for the image created using following javascript.

thanks for any help or replies.

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

Try this:

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

Create an a element in the same fashion. Append it to el instead of the image and append the image to it.

You need to first create a anchor element then append the img element to it... like so:

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

Then append the anchor to 'el'

Matt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM