简体   繁体   中英

How to stop page load while clicking on link with href=#?

i have FAQ page with more than 20 questions.it works as when i click on any question,it shows answer,when i click question again it hides the answer.i used javascript which show/hide the division.

<script>
function showHideDiv(id){
var obj = document.getElementById(id);
if (obj.style.display=="none"){
  obj.style.display='block';
} else if(obj.style.display=="block"){
  obj.style.display='none';
}
}
</script>

and here is the html Code,

<h5><a href="#" onclick="showHideDiv('div-7')">Question No.7</a></h5>
    <div id="div-7" style="display:none;">Answer No.7</div><br>

    <h5><a href="#" onclick="showHideDiv('div-8')">Question No.8</a></h5>
    <div id="div-8" style="display:none;">Answer No.8</div><br>

Now the problem is when i click question 1 to 5,it works perfect,but when i scroll page down and click question no. 7 to 22,due to "#" in href attribute of ,page reloads and scroll back to top,instead of showing the opened answer.so i want something like the page should not be refreshed,but should stay on whichever question is clicked.

You need to return false on click.

<h5><a href="#" onclick="showHideDiv('div-7'); return false;">Question No.7</a></h5>

or

<h5><a href="#" onclick="return showHideDiv('div-7')">Question No.7</a></h5>

and return false in showHideDiv

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