页面跳转到顶部onclick [英] Page jumps to the top onclick
问题描述
我在网站中间点击一下,代码如< a href =#onclick =...
I have a click in the middle of a website with code like <a href="#" onclick="…
该函数效果很好,但是当我点击链接时,a href =#让页面总是跳到顶部。周围有什么方法吗?
The function works well, but the a href="#" let’s the page always jump to the top when I click on the link. Is there any way around it?
谢谢
推荐答案
只需添加;返回false;
到 onclick
的末尾,例如:
Just add ; return false;
to the end of your onclick
, for example:
<a href="#" onclick="alert('hello'); return false;">
编辑:Hemlock的答案是一个不错的选择,但另一个是两者的组合:
Edit: Hemlock's answer is a good alternative, but yet another one is a combination of the two:
<a href="javascript:void(0)" onclick="alert('hello')">
这样做的好处是你明确地说< a>
不应对href执行任何操作,并且onclick事件处理程序是一个单独的属性。如果您以后决定使用JavaScript附加onclick处理程序而不是内联它(推荐),那么只需删除onclick属性即可。
The advantage of this is that you're explicitly saying that the <a>
should do nothing with the href, and the onclick event handler is a separate attribute. If you later decide to attach the onclick handler using JavaScript rather than inlining it (recommended), it's simply a matter of removing the onclick attribute.
这篇关于页面跳转到顶部onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!