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

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

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

Click here !
16条回答
  •  盖世英雄少女心
    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);
    }
    

提交回复
热议问题