使 id 链接可见 - 防止单击定位点时发生默认事件

Making id link visible - Preventing the default event when the anchor is clicked.

本文关键字:定位 事件 默认 单击 链接 id      更新时间:2023-09-26

一个非常简单的问题,但我想不出在谷歌上搜索的"正确"词。我的问题是我想使链接"历史记录"在单击后仍然可见。我不希望页面下降到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
});

页面移动的原因是,这是锚点上单击事件的默认操作。您需要做的是确保默认操作不会发生(这是导致页面上"移动"的原因。我建议如下:

<!-- 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();
});

你不需要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 将它们联系在一起。