简体   繁体   中英

Javascript img tag src switch function not working

I have a small app the uses 3 images as buttons, the images are different colors, above the image buttons there is a big pair of glasses, depending on what color button you press the color of the glasses will change to match the color of the button that was pressed. The problem is I am getting a "Cannot set src to null" error.

Here is a jsfiddle: http://jsfiddle.net/vAF8S/

Here is the function

//Functions that change the glasses image
function changeColor(a){
    var img = document.getElementById("imgG");
    img.src=a;
}

you have two Id's for the tag. you should have only one ID. change your html.

<section id="banner" >

        <img id="imgG" src="images/orangeG.png"><br>
        <img id="wcolorButton" src="images/whiteT.png"  />
        <img id="bcolorButton" src="images/blueT.png" />
        <img id="ocolorButton" src="images/orangeT.png"  onClick="changeColor('images/whiteG.png')" />
    </section>

FIDDLE

you are getting this error because you have applied ID twice to the same element

use this HTML

<section id="banner" >
    <img class="glasses" id="imgG" src="images/orangeG.png"><br>
    <img class="wcolorButton" src="images/whiteT.png"  />
    <img class="bcolorButton" src="images/blueT.png" />
    <img class="ocolorButton" src="images/orangeT.png"  onClick="changeColor('images/whiteG.png')" />
</section>

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