简体   繁体   中英

Set img src of another page using javascript

I am trying to change the src of an image using javascript. The image and the javascript function are in different html pages. The javascript function is given below

     <html>
     <head>
     <script type="text/javascript">
     function changeImage(newSrc)
     {
     document.getElementById(dp).src = newSrc;
     }
     </script>
     <title>Socialize-Home</title>
     </head>
     <body>
     <img id="img1" src = "home images\student1.JPG" onclick="changeImage(this.src)"></img>
     </div>
     </body>
     </html>

The image of another page is given below

<img id="dp" src="home images\unknown user.JPG" alt="Your browser doent support this           
          image !" height="25%" width="15%"/>

You need to have some reference to the other window, for instance you can have the window set opener.childwindow = self in the window with the target image. Or whatever you have to do.

Then it's just referenceToOtherWindow.document.getElementById('dp').src = newSrc;

If you're using AJAX, it puts the second page into the first. There is therefore no need to do anything special. The AJAX'd in content is inside the page and so can be accessed how you would normally access elements.

Therefore your idea should work. However, you have a slight syntax error:

document.getElementById(dp).src = newSrc;

should be:

document.getElementById('dp').src = newSrc;

dp is a string, you haven't defined a variable called dp .

On a side note, the alt tag for an image isn't really anything to do with your browser "not supporting" images. The alt text is displayed if the image is missing or if the user is visually impaired and is using a screen reader.

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