Jquery stop delegated event from calling twice

My JS looks something like this:

$(document).ready(function(){
    menuClickHandler();
});

I have an ajax based menu, menuClickHandlerused to make it work and is in a separate JS file. menuClickHandlerlinks other functions related to a menu item. When a menu item is clicked, it calls the function associated with the menu item. Suppose I have a menu item Jumpand a function associated with it JumpHandler. Inside JumpHandlerthere is one simple function:

functionA() {
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
    });
}

Scenario: When the page is first loaded, everything is fine, when I click Jump functionA' gets called and everything works fine. Now if click some other menu item and then click onGo again,JumpHandler is called again and hencefunctionA` is called again, as a result of which the click event on the branch is connected twice. Can someone tell me how to remove / remove the release of a delegated click event so that only the click event associated with the branch is associated.

jQuery version: v2.1.1

+4
source share
3 answers

You can use .one()instead.on()

Attach a handler to the event for elements. A handler is executed no more than once for each type of event.

code

$("div.tree").one("click", ".branch", function(event) {
    event.stopPropagation();
    //some code
});
+2
source

- click functionA, off

functionA() {
    $("div.tree").off("click", ".branch" );
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
    });
}

functionA, , functionA

, ,

functionA() {
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
       $("div.tree").off("click", ".branch" );
    });
}
+1

Because after calling the function, you initialize the function in jquery, which will be executed without calling the function again. So before calling any function, just disable the jquery function

example:

$("div.tree").off("click", ".branch" );
functionA();

$("div.tree").off("click", ".branch" );
functionB();
0
source

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


All Articles