Is it possible to stop the browser from following the link when the onclick of the child element fires?

后端 未结 4 1646
挽巷
挽巷 2020-12-09 16:59

This is what I have basically:


    stuff
    more          


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 17:43

    To cancel a click on a link, the best practice is to do these two things in your link handler...

    1. Use event.preventDefault().
    2. Return false

    Explanation

    Both of these should be, by themselves, sufficient, but both are documented and well-used. Using both guarantees ideal cross-browser compatibility. To quote the MDN Developer Documentation on event.returnVal...

    The Event property returnValue indicates whether the default action for this event has been prevented or not. It is set to true by default, allowing the default action to occur. Setting this property to false prevents the default action. (Source: MDN Web Docs: Event.returnValue.)

    And the documentation on event.preventDefault...

    The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Web Docs: Event.preventDefault().)

    I was mostly inspired to answer because no other answers had working demos, so here you are! (in JavaScript and jQuery)

    JavaScript

    document.getElementById('move-button').onclick = function(e) {
        if(confirm('Are you sure you want to goto the bottom of page?')) {
        console.log("Click allowed!");
            return true;
        }
        console.log("Click cancelled!");
        e.preventDefault();
        return false;
    };
    Goto Bottom of Page
    
    





    page.1





    page.2





    page.3





    page.4





    page.5





    page.6





    page.7





    page.8





    Bottom of Site

    jQuery

    $('#move-button').on('click', function(e) {
        if(confirm('Are you sure you want to goto the bottom of page?')) {
        console.log("Click allowed!");
            return true;
        }
        console.log("Click cancelled!");
        e.preventDefault();
        return false;
    });
    
    Goto Bottom of Page
    
    





    page.1





    page.2





    page.3





    page.4





    page.5





    page.6





    page.7





    page.8





    Bottom of Site

提交回复
热议问题