problem with javascript: return false is not working

落爺英雄遲暮 提交于 2019-11-28 01:28:05

Change your code as

<a class="button" href="Cancel" onclick="return clearForm()">Cancel</a>

Your problem is you need to return the Boolean.

But, drop all that...

  • Attach your event unobtrusively...

    element.onclick = clearForm;

  • Use preventDefault(). It is the modern way of acheiving that.

    function clearForm(event) { event.preventDefault(); }

<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>

should work

Please note that if there is a bug or error in clearForm() then "return false" will NOT stop the anchor action and your browser will try to link to the href "Cancel". Here is the logic:

  1. User clicks on anchor
  2. onClick fires clearForm()
  3. There is an error in clearForm() so Javascript crashes and stops all code execution.
  4. return false is never fired because Javascript has already stopped.

If you are relying on a third party JavaScript API (I was using code supplied by Recyclebank to spawn a popup), and the third party API makes an update that breaks the JavaScript, then you'll have problems.

The following will stop the link under normal conditions and error conditions.

<a class="button" href="javascript:;" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>

Keep in mind that some browser extensions may interfere with proper operation of links. For example, I ran into a situation where someone had both AdBlock Plus and Ghostery enabled. Clicking a simple 'a' tag with an 'onclick="return SomeFunction();"' attribute (the function returned false) caused the browser to treat the click as a page transition and went to a blank page and the loading indicator just kept spinning. Disabling those browser extensions cleared up the problem.

Including this as an answer because this was the first page I landed on from Google.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!