Javascript return false onclick 锚点没有完全工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5644665/
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
The return false onclick anchor not completely working
提问by RonnieT
I have a lightbox overlay and I'm using the below to cancel out the browser window scroll for the href anchor of "#". I have it working so it doesn't scroll the window on the initial click however upon closing the lightbox overlay the browser scrolls to the top and # is appended to the URL.
我有一个灯箱覆盖,我正在使用下面的内容来取消浏览器窗口滚动以获取“#”的 href 锚点。我让它工作,所以它不会在初始点击时滚动窗口,但是在关闭灯箱覆盖时,浏览器滚动到顶部并且 # 附加到 URL。
<a href="#" onclick="somefunction(); return false;">...
or even this...
甚至这个……
<a href="javascript:void(0)" onclick="somefunction(); return false;">...
The link is on a clickable image which the onclick function fires the overlay to pop up.
该链接位于一个可点击的图像上,onclick 函数会触发覆盖层弹出。
Andy ideas how to prevent the browser from scrolling to top upon exiting the overlay?
Andy 的想法是如何防止浏览器在退出叠加层时滚动到顶部?
回答by DA.
I'd suggest not using an anchor tag at all. If you don't want an HREF value, then it's really not a link to another page, so probably not truly a link. If the site has to be accessible sans javascript, then you need to think about this some more and come up with a solution that will allow for a true href value that will link to the actual content.
我建议根本不要使用锚标记。如果您不想要 HREF 值,那么它实际上不是指向另一个页面的链接,因此可能不是真正的链接。如果该站点必须可以在没有 javascript 的情况下访问,那么您需要多考虑一下并提出一个解决方案,该解决方案将允许链接到实际内容的真正 href 值。
However, if you're OK with this being a JS-required app, then you can do this:
但是,如果您认为这是一个需要 JS 的应用程序,那么您可以这样做:
<a href="javascript:;" onclick="somefunction(); return false;">
But, again, this is really something you are clicking on to update the UI rather than go somewhere, so I'd just make it a DIV, give it an onclick event, and be done with it. But be sure to give the div a tabindex so that it can be keyboard-accessible.
但是,同样,这确实是您单击以更新 UI 而不是去某处的东西,所以我只是将它设为 DIV,给它一个 onclick 事件,然后完成它。但一定要给 div 一个 tabindex,以便它可以通过键盘访问。
回答by alex
You should avoid the #
href and the javascript:
pseudo protocol.
您应该避免使用#
href 和javascript:
伪协议。
A link should always point to a valid resource.
链接应始终指向有效资源。
If you can't use a more suitable element like button
(as your example suggest), I would use event.preventDefault()
to cancel the default behaviour.
如果您不能使用更合适的元素button
(如您的示例所示),我将使用event.preventDefault()
取消默认行为。