开发者

JavaScript Toggle Image by clicking on Img

开发者 https://www.devze.com 2023-04-02 21:53 出处:网络
Im trying to toggle between two images but need the js to work with many different images. How do I make it with a parameter with the id? This is what I got so far:

Im trying to toggle between two images but need the js to work with many different images. How do I make it with a parameter with the id? This is what I got so far:

JS

    function changeIt(id) 
    {
        var theImg = document.getElementsByTagName('img')[0].src;

        var x = theImg.split("/");
        var t = x.length-1;
        var y = x[t];

        if(y=='red.gif')
        {
            document.images.boxcolor1.src='./pics/green.gif'
        }

          if(y=='green.gif')
        {
            document.images.boxcolor1.src='./pics/red.gif'
        }
    }

HTML

    <a href="#" onclick="changeIt('boxcolor1')"><img src='./pics/green.gif' name='boxcolor1' id='boxcolor1' border='0' /></a>   
    <a href="#" onclick="changeIt('boxcolor2')"><img src='./pics/green.gif' name='boxcolor2' id='boxcolor2' border='0' /><开发者_JS百科;/a>   
    <a href="#" onclick="changeIt('boxcolor3')"><img src='./pics/green.gif' name='boxcolor3' id='boxcolor3' border='0' /></a> 

As you can see now it only works for the first image (boxcolor1).. I want it to work for all images by the name or id tag.

Thanks for all the help!


Try:

function changeIt(id) 
{
    var theImg = document.getElementById(id),
             x = theImg.src.split("/"),
             t = x.length-1,
             y = x[t];

    if(y == 'red.gif')
    {
        theImg.src='./pics/green.gif'
    }

    if(y == 'green.gif')
    {
        theImg.src='./pics/red.gif'
    }
}

Working example:

http://jsbin.com/ugofiz/edit

0

精彩评论

暂无评论...
验证码 换一张
取 消