Jquery unbinding and binding

I just want to disable the ability for the user to click an element for some condition, and then re-link it later for another condition. Here are some of the code I'm 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?

+3
source share
1 answer

It sounds like you really want to just disconnect the first navigation link from work. If this is the case, you just want to:

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

how returning falsefrom the event handler prevents the default browser action (following the link).

Although, if the link is not intended for clickability, do not make it a link, turn it into <span>:

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

(, ).


, , , :

$('#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
    }
}
+4

Source: https://habr.com/ru/post/1783554/


All Articles