problem with [removed] return false is not working

2020-02-01 15:19发布

问题:

Hey there is a link in my program as shown and onclick it calls the function clearform as shown:

Html Code:

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

JavaScript Code:

function clearForm(){
        document.getElementById("subjectName").value = "";
        return false;
    }

return false is not working in this code. actually the first line of the function executed successfully but the return false was failed. I mean page is redirected to url "Cancel".

回答1:

Change your code as

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


回答2:

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(); }



回答3:

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

should work



回答4:

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>


回答5:

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.