简体   繁体   中英

the 'if…else' is not checking any other conditions, directly skipping to last 'else' statement

i,m calling a JavaScript function to change an image by using if..else statement to change its source. but it directly skips to last else statement, so the image only keeps swapping between first & last image

JavaScript function:

function myfunction2() {
    var image = document.getElementById("image");
    //iterartion 1
    if (image.src == "img1.jpg") {
        image.src = "img2.jpg";
    } else if (image.src == "img2.jpg") {
        image.src = "img3.jpg";
    } else if (image.src == "img3.jpg") {
        image.src = "img4.jpg";
    } else if (image.src == "img4.jpg") {
        image.src = "img5.jpg";
    } else if (image.src == "img5.jpg") {
        image.src = "img1.jpg";
    } else {
        image.src = "img2.jpg";
    }
}

html code:

<div id="image-slider">
            <img src="img1.jpg" id="image">

            <div id="left-holder">
            <img onclick="myfunction2()" src="arrow-left.png" height="49px" width="49px" class="left"/>
            </div>

            <div id="right-holder">
            <img  onclick="myfunction2()" src="arrow-right.png" height="49px" width="49px" class="right"/>
            </div>
</div>

what am i doin wrong here? plz help.

Try using trim() function

    function myfunction2() {
        var image = document.getElementById("image");
image = image.trim();
        //iterartion 1
        if (image.src == "img1.jpg") {
            image.src = "img2.jpg";
        } else if (image.src == "img2.jpg") {
            image.src = "img3.jpg";
        } else if (image.src == "img3.jpg") {
            image.src = "img4.jpg";
        } else if (image.src == "img4.jpg") {
            image.src = "img5.jpg";
        } else if (image.src == "img5.jpg") {
            image.src = "img1.jpg";
        } else {
            image.src = "img2.jpg";
        }
    }

I doubt that there might be spaces surrounding your text

In your javascript code image.src gives something like "file:///C:/Users/guser/Desktop/img1.jpg" So instead of if(image.src == "img1.jpg") use if(image.src.indexOf("img1.jpg") != -1)

That means "img1.jpg" is present in absolute path of image.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