如何从<a> tag?

时间:2015-12-02 09:42:34

标签: javascript jquery

First I used window.onbeforeunload on my application. It's working on over page but when click on anchor link it should be disabled <a href="abc.com">Click</a>. Any ideas? Please share. My code is below it is not working:

var submitFormOkay = false;
window.onbeforeunload = function () {
    if (!submitFormOkay) {
        return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
    } else {
        submitFormOkay = '';
    }
}

<a class="navbar-brand" href="http://www.google.com">Click</a>

2 个答案:

答案 0 :(得分:1)

您可以在document.body上附加全局点击处理程序,如果点击通过a元素,则将submitFormOkay设置为true(或者您可以使用其他变量绕过检查,或只是通过将null分配给window.onbeforeunload来清除处理程序,例如:

$(document.body).on("click", "a", function() {
    submitFormOkay = true; // Or set another flag you'll check,
                           // or clear onbeforeunload entirely
});

没有jQuery(因为我最初错过了jquery标签):

document.body.addEventListener("click", function(e) {
    var element;
    for (element = e.target; element != document.body; element = element.parentNode) {
        if (element.tagName.toUpperCase() === "A") {
            submitFormOkay = true; // Or set another flag you'll check,
                                   // or clear onbeforeunload entirely
            break;
        }
    }
}, false);

答案 1 :(得分:-2)

使用jquery可以遵循:

var submitFormOkay = false;
$(window).on('beforeunload',function () {
    if (!submitFormOkay) {`enter code here`
        return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
    } else {
        submitFormOkay = '';
    }
})

<a class="navbar-brand" href="http://www.google.com">Click</a>
$('a').on('click',function(e){
    e.preventDefault();
    $(window).off('beforeunload');
    window.location = $(this).attr('href');
});