简体   繁体   中英

Can't assign html .src to a javascript variable

I'm trying to switch an image on a HTMLbutton using javascript.

It works, but I think it loads the image every time I click the button, and that's not good. So I want to load the images only one time and than I can switch between the images. This Is what I have now.

mute.onclick=function () {

if (audioEngine.isMuted)
    {
    document.getElementById('muteIcon').src="images/unmuted.png";
    }       
         else{
           document.getElementById('muteIcon').src="images/unmuted.png";
             }

But I think every time I click the button it looks in the path "images/unmuted.png" to see what's there and load it. So I was thinking this is an easy fix. I just define a variable unmuteImage and assign that to document.getElementById('muteIcon').src. Like this

var unmuteImage=new Image();
    unmuteImage.src='images/unmuted.png';

mute.onclick=function () {

if (audioEngine.isMuted)
    {
    document.getElementById('muteIcon').src=unmuteImage;
    }       
         else{
           document.getElementById('muteIcon').src="images/unmuted.png";
             }

But when I do this, I get the following error in my consols:

GET file:///path/to/the/mian/html/file/[object%20HTMLImageElement]  (In red text)

And I don't get the image, I get the "borken image" picture because somehow it didn't find the picture.

Can somebody help me please? Thanks

this may work for you if you have jquery

$('#muteIcon').replaceWith(unmuteImage);

other wise you have to use src itself

document.getElementById('muteIcon').src = unmuteImage.src;

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