Using JQuery bindings and binding event listeners is very simple. But when you bind multiple listeners to an event for an element, how do you precisely bind one of the listeners? We need to know the namespace of the event.
Look at the following code:
Copy Code code as follows:
$ (' #element ')
. On (' click ', dosomething)
. On (' click ', Dosomethingelse);
Bind event listeners like the above, and when the elements are clicked, both DoSomething and Dosomethingelse will be triggered. This is a handy place to use jQuery, and you can add different listeners to the same event for the element at any time. Unlike OnClick, the new listener overwrites the old.
If you want to solve one of the listeners, such as dosomething, how do you do it?
Is that right?
Copy Code code as follows:
$ (' #element '). Off (' click ');
Attention! The above line of code will bind all the listeners of the click event of the element, which is not the result we want.
Luckily for JQuery. The off () method can accept the second argument, just like. On (). You can bind the specified listener by passing the name of the listener function as the second argument to the. Off () method.
Copy Code code as follows:
$ (' #element '). Off (' click ', dosomething);
But if you don't know the name of the function, or you're using an anonymous function:
Copy Code code as follows:
$ (' #element '). On (' click ', function () {
Console.log (' dosomething ');
});
How can you accurately bind a click event listener?
First code:
Copy Code code as follows:
$ (' #element '). On (' Click.mynamespace ', function () {
Console.log (' dosomething ');
});
Instead of just passing the click event as a parameter to the. On () method, you specify a namespace for the click event and then listen for the Click event in the namespace. At this point, even if the listener is an anonymous function, it is actually "famous". Now you can solve the event listener in a specific namespace as follows.
Copy Code code as follows:
$ (' #element '). Off (' Click.mynamespace ');
This is one of the more convenient and powerful features of JQuery, and its internal implementation must be fun!