简体   繁体   English

如何在单击带有href =#的链接时停止页面加载?

[英]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. 我有20多个问题的FAQ页面。当我单击任何问题时,它会显示答案,当我再次单击问题时,它将隐藏答案。我使用了显示/隐藏该部门的javascript。

<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, 这是html代码,

<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. 现在的问题是,当我单击问题1至5时,它可以正常运行,但是当我向下滚动页面并单击问题号时。 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. 7到22,由于href属性中的“#”,页面重新加载并滚动回到顶部,而不是显示打开的答案。所以我希望页面不刷新,但无论单击哪个问题,都应保留。

You need to return false on click. 您需要在点击时return false

<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 并在showHideDiv return false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM