最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop page load while clicking on link with href=#? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Aug 5, 2013 at 10:57 8bitrebellion8bitrebellion 1801 gold badge2 silver badges12 bronze badges 2
  • A bit of research and this shows up. – Patsy Issa Commented Aug 5, 2013 at 11:00
  • thanks for finding it out, and sorry i repeated same question again.i couldnt found it on first place. – 8bitrebellion Commented Aug 5, 2013 at 11:12
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论