Frage

I have a link with the text "No New Notifications". The following code is used to make the link not clickable:

if ($.trim($('a#full_notifications_link').text()) == "No New Notifications"){
    $('a#full_notifications_link').click(function(){
        event.preventDefault();
        return false;
    });
}

I am using Ajax to poll the server and update the text. When the text is updated to say "See All Notifications", I want the link to become clickable. I am using the following code, but it is not working.

$(document).ajaxComplete(function(){
    if ($.trim($('a#full_notifications_link').text()) == "See All Notifications"){
        $('a#full_notifications_link').click(function(){
            return true;
        });
    }
});

I know the problem has something to do with returning true, because if i put an alert in right before returning true, the alert works. Unfortunately, the link is still unclickable.

I also CANNOT change any of my html because it is generated differently every time by the backend.

War es hilfreich?

Lösung

Adding a new event handler does not remove the event handlers you already have, so the default action is still prevented.

Use on() and off() instead

if ($.trim($('a#full_notifications_link').text()) == "No New Notifications"){

    $('a#full_notifications_link').on(function(event){
        event.preventDefault();
    });
}

$(document).ajaxComplete(function(){
    if ($.trim($('a#full_notifications_link').text()) == "See All Notifications"){

        $('a#full_notifications_link').off('click');

    }
});

It does seem easier to just check the text inside the event handler

$('a#full_notifications_link').on('click', function(e) {
     if ( $.trim($(this).text())  == "No New Notifications"){
         e.preventDefault();
     }
});

Andere Tipps

Could you just move your logic into the click handler?

$('a#full_notifications_link').click(function(evt){
    if($(this).text() == "No New Notifications") {
        evt.preventDefault();
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top