开发者

Re-enable event handler for a link

开发者 https://www.devze.com 2023-03-19 20:19 出处:网络
I want to disable a link while certain conditions exist on the page, but re-enable it once those conditions go away. So I have a function that executes regularly that checks for the condition.

I want to disable a link while certain conditions exist on the page, but re-enable it once those conditions go away. So I have a function that executes regularly that checks for the condition.

if(!enabled) {
$(button).click(function(){return false;});
}

How do I "re-enable" that click event so that it performs th开发者_StackOverflow中文版e normal action? All I want it to do is behave like a normal link.


You can put a custom event namespace on your link, and bind/unbind it when necessary:

Disabling:

$('#thelink').on('click.MyDisable', function () {
    return false; 
});

Enabling:

$('#enabler').on('click', function () {
    $('#thelink').off('click.MyDisable');
});

Please check out the jsFiddle Demo.


Put your condition inside the event:

$(button).click(function(){
    if(!enabled) {
        return false;
    }
});


You could do your check within the button click:

$(button).click(function(){ 
    if(!enabled) 
        return false;
});


I would set the disabled attribute to disabled when you want to disable the link, and remove the attribute when want to enable it. The only problem is the link will appear disabled, but the user can still click on it. So in addition to that in the click event handler I would check for the following condition:

$("#myLink").click(function(){
   if($(this).attr("disabled"))
      return false;
});

in your checks you can either do this:

$("#myLink").attr("disabled", "disabled");//if you want to disable it

$("#myLink").removeAttr("disabled");//if you want to enable it
0

精彩评论

暂无评论...
验证码 换一张
取 消