简体   繁体   中英

How to Change IMG using Javascript

I wanted to change the image using javascript only without changing anything on the html

here is the HTML

<td bgcolor="#2A2A1B" style="width: 128px;" valign="top">
    <img id="ContentPlaceHolder1_imgClanmark" src="../images/clan/clanmark20130211202115640.png" style="height:128px;width:128px;" />
</td>

now here is my js

var photo = document.getElementById('ContentPlaceHolder1_imgClanmark');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://i.imgur.com/jztMCqb.png';
photo.src = img.src;

tried it and it wont work

also used this

function FirstPic()
{
    var pic1 = document.getElementById("ContentPlaceHolder1_imgClanmark"); 
    if (pic1 == typeof('image')) return;
    pic1.src = "http://i.imgur.com/jztMCqb.png";
}

but then again I should add codes on html like

<img onload='FirstPic()' id='ContentPlaceHolder1_imgClanmark' src='http://i.imgur.com/jztMCqb.png' />

Can someone help me on this one?


I'm sorry I haven't updated this question here is what I did

--

window.onload = function() {
  var photo = document.getElementById('ContentPlaceHolder1_imgClanmark');
  var img = new Image();
  img.src = 'http://i1203.photobucket.com/albums/bb384/zendesigns/sfdfi/sfdfilogo_zps9302a288.gif';
  img.addEventListener('load', myFunction, false);
  function myFunction() {
   photo.src = img.src;
  }
}

--

Thanks Stano

Is there a reason you're waiting for the onload event if this is on first pageload ?

document.getElementById('ContentPlaceHolder1_imgClanmark').src = 'http://i.imgur.com/jztMCqb.png';

will change the source ?

EDIT:

On the other hand the image on this link : http://i.imgur.com/jztMCqb.png can not be hotlinked, and returns 403 forbidden when you try to link to it, so that image will never show up no matter what you do!

只需更改src:

    $("#ContentPlaceHolder1_imgClanmark").attr("src","pass_here_new_image_source");

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