我目前使用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()。
其他回答
你也可以在处理jquery后返回false。
Eg.
$(".clickableAnchor").live(
"click",
function(){
//your code
return false; //<- prevents redirect to href address
}
);
只使用
<a href="javascript:;" class="someclass">Text</a>
JQUERY
$('.someclass').click(function(e) { alert("action here"); }
我总是用:
<a href="#?">Some text</a>
当试图阻止页面跳转时。不确定这是否是最好的,但它似乎已经工作了很多年。
带有href="#"的链接几乎总是应该被按钮元素替换:
<button class="someclass">Text</button>
使用带有href="#"的链接也是一个可访问性问题,因为这些链接将对屏幕阅读器可见,屏幕阅读器将显示“链接-文本”,但如果用户单击它,它不会去任何地方。
在jQuery中,当你处理点击事件时,返回false以阻止链接响应通常的方式阻止默认操作,即访问href属性,从发生(根据PoweRoy的评论和Erik的回答):
$('a.someclass').click(function(e)
{
// Special stuff to do when this link is clicked...
// Cancel the default action
e.preventDefault();
});