我目前使用jQuery的<a>标签来启动像点击事件等事情。
例如<a href="#" class="someclass">Text</a>
但我讨厌“#”使页面跳转到页面顶部。我能做什么呢?
我目前使用jQuery的<a>标签来启动像点击事件等事情。
例如<a href="#" class="someclass">Text</a>
但我讨厌“#”使页面跳转到页面顶部。我能做什么呢?
当前回答
有4种类似的方法可以防止页面在不使用JavaScript的情况下跳转到顶部:
选项1:
<a href="#0">Link</a>
选项2:
<a href="#!">Link</a>
选项3:
<a href="#/">Link</a>
选项4(不推荐):
<a href="javascript:void(0);">Link</a>
但是如果你在jQuery中处理点击事件,最好使用event. preventdefault()。
其他回答
如果你想使用一个锚,你可以像其他答案一样使用http://api.jquery.com/event.preventDefault/。
您还可以使用任何其他元素,如span,并将单击事件附加到它。
$("span.clickable").click(function(){
alert('Yeah I was clicked');
});
如果你想要迁移到同一页面上的锚节,而不需要页面跳转,请使用:
只要用“#/”而不是“#” 如
<a href="#/home">Home</a>
<a href="#/about">About</a>
<a href="#/contact">contact</a> page will not jump up on click..
为了防止页面跳转,你需要调用e.s stoppropagation ();在调用e.b epreventdefault()之后:
stopPropagation阻止事件沿着DOM树向上移动。更多信息请访问:https://api.jquery.com/event.stoppropagation/
您可以使用event.preventDefault()来避免这种情况。更多信息请点击:http://api.jquery.com/event.preventDefault/。
$('a[href="#"]').click(function(e) {e.preventDefault(); });