[英]Making id link visible - Preventing the default event when the anchor is clicked.
一个非常简单的问题,但我想不出要在Google上搜索的“正确”字词。 我的问题是单击链接后,仍要使“历史记录”链接仍然可见。 我不希望页面下降到div,而只是更改内容。 我知道我需要jquery来隐藏/切换内容,但是我被困在链接部分。
#goals{
display : none;
}
#history{
display : block;
}
<p ><a id="History" href="#history"> <b>History</b> </a></p>
<p ><a id="Goals" href="#goals"> <b>Goals</b> </a></p>
<div id="history">
<p> blah blah blah </p>
</div>
<div id="goals">
<p> blah blah blah </p>
</div>
$("#Goals").click(function(){
$("#history).hide();
$("#goals").show();
})
您需要在传递给处理程序的事件参数上调用preventDefault()
方法。 例如:
<a id="historyLink" href="#">History</a>
...和...
$('#historyLink').click(function(e){
e.preventDefault(); // block the default action
// do something
});
您不需要CSS,可以使用jQuery完成所有操作:
HTML
<p ><a id="History" href="#history"> <b>History</b> </a></p>
<p ><a id="Goals" href="#goals"> <b>Goals</b> </a></p>
<div id="history">
<p> history blah blah blah </p>
</div>
<div id="goals">
<p> goals blah blah blah </p>
</div>
jQuery的
$("#goals").hide();
$("#Goals").click(function(){
$("#history").hide();
$("#goals").show();
});
$("#History").click(function(){
$("#goals").hide();
$("#history").show();
});
这是将所有内容绑定在一起的jsFiddle 。
页面移动的原因是,这是锚点上的click事件的默认操作。 您需要做的是确保不会发生默认操作(这是页面上“移动”的原因。我建议以下几点:
<!-- you don't need to link it to the actual id, since you are toggling the visibility using jQuery -->
<a id="historyLink" href="#">History</a>
然后,就jQuery而言:
$('#historyLink').click(function(event){
//prevent the page from scrolling
event.preventDefault();
//possibly hide the other div if it is visible
$('#theotherdiv').hide();
//show the div
$('#historyLink').show();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.