开发者

jquery unbinding and binding

开发者 https://www.devze.com 2023-02-02 05:51 出处:网络
I just want to disable the ability for a user to click on an element for some con开发者_StackOverflow中文版dition and then re-bind it later for another condition. Here is some of the code I am working

I just want to disable the ability for a user to click on an element for some con开发者_StackOverflow中文版dition and then re-bind it later for another condition. Here is some of the code I am working with:

 $('#navigation a').bind('click',function(e){

    var $this   = $(this);
    var prev    = current;

    current = $this.parent().index() + 1;

    if (current == 1){
       $("#navigation a:eq(1)").unbind("click"); // remove the click for element
    }
    if (current >= 2){
       $("#navigation a:eq(1)").bind("click"); // this doesn't work, but i want re-bind the click here.
    } }

What do I need to do to make this work?


It sounds like you actually want to just disable the first navigation link from working. If that's the case, you simply want:

$("#navigation a:first").click(function () { return false; });

as returning false from an event handler prevents the browser's default action (of following the link) from occuring.

Although, if the link is not meant to be clickable, don't make it a link, turn it into a <span>:

var link = $("#navigation a:first");
$("<span>").text(link.text()).attr("class", link.attr("class"))
    .insertBefore(link);
link.remove();

(assuming that the class attribute of the link is the only worthy attribute to copy).


If you actually do wish to unbind the custom handler you wrote, then you want to give the handler function a name so it can be referenced again for rebinding:

$('#navigation a').bind('click', onClick);

function onClick(e) {
    var $this   = $(this);
    var prev    = current;

    current = $this.parent().index() + 1;

    if (current == 1){
       $("#navigation a:eq(1)").unbind("click"); // remove the click for element
    } else {
       $("#navigation a:eq(1)").bind("click", onClick); // use the function again
    }
}
0

精彩评论

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

关注公众号