简体   繁体   中英

Strange behavior with URL fragments and onclick in iOS Safari

I have run into a strange problem in mobile Safari on my (iOS 4) iPod touch. The minimum body HTML to demonstrate this problem is:

<p>
    <a href="" onclick="event.preventDefault()">Click</a>
</p>
<p id="anchor">
    Anchor
</p>

When the page is loaded with no # fragment in the URL, clicking the link executes the onclick javascript, which suppresses the action of the link, and (as expected) nothing happens.

However, if the page is loaded with a valid URL fragment, #anchor in the above example, then clicking on the link causes the page to jump to the paragraph with id 'anchor' (like when the page was initially loaded).

I cannot find a way round this; any suggestions would be greatly appreciated.

It's because href="" (not correct) is the same as href="." (correct) which is the same thing than putting the current url in the href.

If you were just trying to make a button, you could use a <span> with some CSS like cursor: pointer and such things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM