Html <a href onClick="return false;"> 在 Safari/iOS 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10152577/
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
<a href onClick="return false;"> not working in Safari/iOS?
提问by Gadi A
I have this code in my page:
我的页面中有此代码:
<a href onClick="return false;">Press me!</a>
The link is placed inside a span with a useful onClick event.
链接被放置在一个带有有用的 onClick 事件的跨度内。
Now, in Chrome and Firefox this works perfectly. The link is clicked, the useful event is executed and everybody's happy. In iOS (iPhone and iPad) using the default Safari browser, this fails miserably - after the link is clicked the whole page is reloaded and the useful event is never executed.
现在,在 Chrome 和 Firefox 中,这可以完美运行。单击链接,执行有用的事件,每个人都很高兴。在使用默认 Safari 浏览器的 iOS(iPhone 和 iPad)中,这会失败得很惨 - 单击链接后,整个页面会重新加载,并且永远不会执行有用的事件。
I also tried
我也试过
<a href="#" onClick="return false;">Press me!</a>
Which I understood to be the wrong way of doing this. In Chrome and Firefox it works well, but in iOS' Safari it jumped back to the beginning of the page (but it DID execute the useful event, so in a sense it was better).
我认为这是错误的做法。在 Chrome 和 Firefox 中它运行良好,但在 iOS 的 Safari 中它跳回到页面的开头(但它确实执行了有用的事件,所以从某种意义上说它更好)。
What am I missing?
我错过了什么?
采纳答案by Gai
From your description, it seems like a bug in iOS browser JS implementation (maybe create a minimal code to demonstrate it?).
从您的描述来看,这似乎是 iOS 浏览器 JS 实现中的一个错误(也许创建一个最少的代码来演示它?)。
A simple workaround would be to replace the <a href...>
with <span style="cursor:pointer;">
.
一个简单的解决方法是更换<a href...>
用<span style="cursor:pointer;">
。
回答by wjl
You can set href="#"
, and I'm noticing the same jumping to the top of the page. #
is an in-page anchor, which I believe refers to the top of the page. I'm not clear on the defined behavior for that. But alas, you want to cancel it.
您可以设置href="#"
,我注意到同样跳转到页面顶部。#
是页内锚点,我相信它指的是页面顶部。我不清楚为此定义的行为。但是,唉,你想取消它。
In the iPhone 5.0.1 Simulator, combining both cancelation methods works and doesn't scroll to the top. This is my complete test.html
file. It works in the simulator, Chrome and OS X Safari.
在 iPhone 5.0.1 Simulator 中,结合两种取消方法有效并且不会滚动到顶部。这是我的完整test.html
文件。它适用于模拟器、Chrome 和 OS X Safari。
<div style="height: 1000px; background-color: blue;"></div>
<a href="#" onClick="event.preventDefault(); return false;">Poke it!</a>
<div style="height: 1000px; background-color: red;"></div>
For the record, removing the event.preventDefault();
duplicates your bug.
作为记录,删除event.preventDefault();
重复的错误。
回答by GillesC
Have you tried binding the element purely from javascript?
您是否尝试过纯粹从 javascript 绑定元素?
<a href="#" id="nogo">Foo</a>
document.getElementById('nogo').onclick = function(ev) {
ev.preventDefault();
};