javascript 页面跳转到顶部 onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4724408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Page jumps to the top onclick
提问by Denise
I have a click in the middle of a website with code like <a href=“#“ onclick=“…
我在网站中间点击一下,代码如下 <a href=“#“ onclick=“…
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?
该功能运行良好,但是a href="#" 让我点击链接时页面总是跳到顶部。有什么办法可以解决吗?
Thanks
谢谢
回答by David Tang
Just add ; return false;to the end of your onclick, for example:
只需添加; return false;到您的末尾onclick,例如:
<a href="#" onclick="alert('hello'); return false;">
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')">
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.
这样做的好处是您明确表示不<a>应对 href 执行任何操作,并且 onclick 事件处理程序是一个单独的属性。如果您稍后决定使用 JavaScript 附加 onclick 处理程序而不是内联它(推荐),则只需删除 onclick 属性即可。
回答by Hemlock
Alternate method
替代方法
<a href="javascript: alert('hello'); void(0);"></a>
Put the javascript in the href and make sure the code ends in a call to void
将 javascript 放在 href 中并确保代码以调用结束 void
回答by Umair Jabbar
add
添加
return false;
at the end of the onclick statement
在 onclick 语句的末尾
that is
那是
<a href="#" onclick="alert('test'); return false;"> Click Here </a>
回答by Bazzz
if you want an element that does some javascript onclick, you should not use the atag. The atag is for navigation from one page to another. You should use spanand then you don't have to provide a hrefattribute. The problem lies in the fact that you chose the wrong HTML element for your case.
如果您想要一个执行某些 javascript 的元素,则onclick不应使用该a标签。该a标签用于从一个页面导航到另一个页面。您应该使用span然后不必提供href属性。问题在于您为案例选择了错误的 HTML 元素。
<span onclick=""></span>

