This article analyzes the solution to jQuery's repeated binding events. Share it for your reference, as follows:
1. Question:
Today, I found that the event of a jQuery object can be repeatedly bound multiple times, and when the event is triggered, the code will be executed multiple times.
Here is an example of a click event being repeatedly bound:
function reg_button_click(){ $("#button).click(function(){ alert("button click"); }); } $(document).ready(function(){ #Repeat registration 3 times reg_button_click(); reg_button_click(); reg_button_click(); #When triggered, 3 alerts appear $('#button').click(); });
2. Solution:
For scenarios that require repeated binding, when registering events, consider using the method of unbind and then bind first; or off first and on
function reg_button_click(){ $("#button).unbind('click').bind('click',(function(){ alert("button click"); }); } $(document).ready(function(){ #Repeat registration 3 times reg_button_click(); reg_button_click(); reg_button_click(); #When triggered, 3 alerts appear $('#button').click(); });
For more information about jQuery, please view the special topic of this site: "Summary of jQuery operation xml skills》、《Summary of jQuery drag and drop special effects and skills》、《Summary of jQuery extension skills》、《Summary of common classic effects of jQuery》、《Summary of jQuery animation and special effects usage》、《Summary of jquery selector usage"and"Summary of commonly used plug-ins and usages of jQuery》
I hope this article will be helpful to everyone's jQuery programming.