简体   繁体   中英

Clicking on a link, takes me to the bottom of the page instead of the place from where I called it

As soon as I click on 'Hide' link below, my page goes to the bottom. How can I make it go to the place from where it opened?

My code:

<li><a href="javascript:ReverseDisplay('basic2')">How do I maximize battery life?</a></li>

<div id="basic2" style="display:none; background-color:#fff; padding:5px; margin-left: 11px;">
    <p>Wadfasfsafasfas</p>
    <a href="#" onclick="ReverseDisplay('basic2');">Hide</a></li>
    <div id="basic2" style="display:none; background-color:#fff; padding:5px; margin-left: 11px;">
    </div>
    <p>&nbsp;</p>
    <hr />
</div>

Function:

function ReverseDisplay(d) {
    if(document.getElementById(d).style.display == "none")
    {
        document.getElementById(d).style.display = "block";
    }
    else
    {
        document.getElementById(d).style.display = "none";
    }
}

Whenever you have an onClick in a link (like onclick="ReverseDisplay('basic2');" you want to make sure it returns false .

Something like this should work : onclick="ReverseDisplay('basic2');return false;"

You've got duplicate element ids "basic2"

Edit I think what you're looking for is something like this. Where "Hide" toggles the parent element:

<li><a href="javascript:ReverseDisplay('basic1')">How do I maximize battery life?</a></li>
<div id="basic1" style="display:none; background-color:#fff; padding:5px; margin-left: 11px;">
    <p>Wadfasfsafasfas</p>
    <a href="#" onclick="ReverseDisplay('basic1');">Hide</a></li>
    <p>&nbsp;</p>
    <hr />
</div>
<script>
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
</script>

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