简体   繁体   中英

jQuery on/off click

I need to intercept a click on the page and execute some validation logic and let the flow go on.

I have a link:

<a data-link="true">Link</a>

Js to intercept:

$("a[data-link='true'").off("click.link").on("click.link", (event) => this.validate(event));

In validate function I just make some validations and I need to proceed with the request.

How can I intercept the click and If validation it's ok, proceed with the original request ?

Thanks.

Your data selector might do better if it was more generalized:

$(function(){
    // Listen for data link in general
    $('a[data-link]').on('click',function(e){
        // Stop all request
        e.preventDefault();
        // Get the link href
        var hrefPath    =   $(this).attr('href');
        // If the data-link is set to true
        if($(this).data('link') === true) {
            // Do your validation here, not sure if your validation function
            // works or not, but here is where you apply it
            var valid   =   true;
            // If failed, set the default path to empty
            if(!valid)
                hrefPath = false;
            // If the path is not empty, go to the default path
            if(hrefPath !== false)
                window.location =   hrefPath;
            // Stop
            return false;
        }
        // If the link is not true, just go to the default path
        window.location =   hrefPath;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM