简体   繁体   中英

Changing location.href in javascript using if statement

We have kept a scroll view inside a division tag. Only one paragraph should appear inside the division tag. When the next button is pressed the next paragraph should appear.

We have used location.href property to go to the next paragraph. When the button is clicked once it goes to the second paragraph, but when it is clicked for the second time it stays there and does not go to the third paragraph. What do you think is the problem ?

My Code :

    <body>
     <div>
    <p id="one">HI</p>
    <p id="two">Hello</p>
    <br><br><br><br><br><br><br><br>
    <p id="three">Howdy</p>
</div>
<button type="button" onclick="next()">Next</button>
</body>



div{
        border: 1px solid black;
        height: 200px;
        width: 500px;
        overflow: auto;
    }



function next () {
        if (location.href="#one") {
            location.href="#two";
        }
         else if (location.href==="#two") {
            location.href="#three";
        } }

Small mistake,typo maybe... ?

if (location.href="#one")

to this:

if (location.href=="#one") {
        location.href="#two";
    }
     else if (location.href==="#two") {
        location.href="#three";
    } }

You need to use conditional operator == not assignment operator =

if (location.href == "#one") {
    location.href = "#two";
} else if (location.href === "#two") {
    location.href = "#three";
}

Here is the complete solution..

you need to find fist contain '#' (hashtag) or not..

like

   function next () {

var hashtag =location.href.split('#');
// check array leangth if >1
if(hashtag.length>1)
{
       var hashtagval = hashtag[1];

        if (hashtagval=="one") {
            location.href="#two";
        }
         else if (hashtagval=="two") {
            location.href="#three";
        } 


//and so on
}
    else
    {
       location.href="#one";
    }
}
function next () {
if (location.href.indexOf('one') != -1) {
    location.href="#two";
}
else if (location.href.indexOf('two') != -1) {
    location.href="#three";
} 
else{
    location.href="#one"
}

}

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