What's the effect of adding 'return false' to a click event listener?

前端 未结 16 1751
南旧
南旧 2020-11-21 22:59

Many times I\'ve seen links like these in HTML pages:

Click here !
相关标签:
16条回答
  • 2020-11-21 23:20

    Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.

    If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.

    0 讨论(0)
  • 2020-11-21 23:21

    Here's a more robust routine to cancel default behavior and event bubbling in all browsers:

    // Prevents event bubble up or any usage after this is called.
    eventCancel = function (e)
    {
        if (!e)
            if (window.event) e = window.event;
        else return;
        if (e.cancelBubble != null) e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
        if (e.preventDefault) e.preventDefault();
        if (window.event) e.returnValue = false;
        if (e.cancel != null) e.cancel = true;
    }
    

    An example of how this would be used in an event handler:

    // Handles the click event for each tab
    Tabstrip.tabstripLinkElement_click = function (evt, context) 
    {
        // Find the tabStrip element (we know it's the parent element of this link)
        var tabstripElement = this.parentNode;
        Tabstrip.showTabByLink(tabstripElement, this);
        return eventCancel(evt);
    }
    
    0 讨论(0)
  • 2020-11-21 23:24

    I believe it causes the standard event to not happen.

    In your example the browser will not attempt to go to #.

    0 讨论(0)
  • 2020-11-21 23:26

    The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

    0 讨论(0)
  • 2020-11-21 23:27

    When using forms,we can use 'return false' to prevent submitting.

    function checkForm() {
        // return true to submit, return false to prevent submitting
    }
    <form onsubmit="return checkForm()">
        ...
    </form>
    
    0 讨论(0)
  • 2020-11-21 23:28

    You can see the difference with the following example:

    <a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a>
    

    Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.

    0 讨论(0)
提交回复
热议问题