简体   繁体   中英

jQuery .off (unbind) not working after event.preventDefault()

The question has not yet been answered with a solution but it still not working for me.

The problem is that I want do disable links if a save button is not clicked (trying to override the onbeforeunload function).

My page structure looks like this :

<ul class="nav">
    <li><a class="noclic" href="..."></a>
    </li>
    <li><a class="noclic" href="..."></a>
    </li>
    <li><a class="noclic" href="..."></a>
    </li>
</ul>
<button type="button" class="save">Save</button>
<form>...</form>
<button type="button" class="save">Save</button>

And here's my jQuery:

$(document).ready(function () {
    $('.noclic').on('click', function (e) {
        //(I also display a confirm modal)
        e.preventDefault();
        var $this = $(this);
        console.log("locked");
    });
    $('.save').click(function () {
        $('.noclic').off('click');
        console.log("unlocked");
    });
});

When I click on the nav links, the console shows the "locked" message. But when the button is clicked, the "unlocked" console shows quickly before vanishing, and the event.preventDefault is still running.

What am I doing wrong ?!

Two issues 1) Your buttons are "submit" buttons, thus, when you click, the page is reloaded. You have to change them to

<button type="button">

2) Your buttons have class "save" but you use $( "#save" ) instead of $( ".save" ) to reference them

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