使 id 链接可见 - 防止单击定位点时发生默认事件
Making id link visible - Preventing the default event when the anchor is clicked.
一个非常简单的问题,但我想不出在谷歌上搜索的"正确"词。我的问题是我想使链接"历史记录"在单击后仍然可见。我不希望页面下降到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 将它们联系在一起。
相关文章:
- 分派点击事件并保留击键修饰符
- 模糊事件的Javascript测试
- keyup事件处理程序更改焦点不适用于快速键入
- 在函数中定位动态创建的HTML元素(用于追加事件 - 而不是点击!)jQuery
- 定位将禁用悬停选择器和鼠标悬停事件
- 定位 d3 上的其他元素.js事件上
- 如何定位锚点“悬停”事件,就像在 jQuery 中的 css a:hover 一样
- 从绝对定位的元素冒泡的鼠标事件
- 定位从中生成事件的元素
- 如何为画布内随机定位的框添加点击事件
- 在处理事件时,如何定位具有特定类的元素
- 如何在javascript DOM事件中定位主体
- 在OSX Safari(适用于Chrome/Firefox)上,滚动事件期间的CSS定位无响应和抖动
- 我怎么能强迫元素在一个固定的定位元素响应javascript的onclick事件在Android web浏览器
- 处理删除事件时如何定位游标索引
- 捕捉html5地理定位事件
- 单击另一个单击事件中的定位标记
- 在发布事件数据时,如何定位要用新数据重置的正确集合
- 谷歌地图-事件监听器创建的标记商店定位器
- 定位触发事件的项目